design patterns
play

Design Patterns Applications Programming What is design patterns? - PDF document

10/26/2011 G52APR Design Patterns Applications Programming What is design patterns? The design patterns are language- Design Patterns 1 independent strategies for solving common object-oriented design problems. Jiawei Li (Michael)


  1. 10/26/2011 G52APR Design Patterns Applications Programming • What is design patterns? – The design patterns are language- Design Patterns 1 independent strategies for solving common object-oriented design problems. Jiawei Li (Michael) email: jwl@cs.nott.ac.uk http://www.cs.nott.ac.uk/~jwl/G52APR 2 Design Patterns Outline • How many design patterns? • Commonly recurring patterns of OO – Many. design • A simple example • Why use design patterns? • Adapter pattern – Solutions to complex problems • Composite pattern – Code reuse • Solving complex problems – To be a good Java developer 3 4 Commonly recurring patterns of OO Bicycles Simulator design • Various bicycles • Creational Patterns – Mountain bicycles o Adaptor – Road bicycles • Structural patterns o Composite – Child bicycles … • Behavioural patterns o Strategy • J2EE patterns o Decorator • Various actions • … o Observer – Speed up o Factory method – Changing gear … o Iterator 5 6 1

  2. 10/26/2011 Bicycle’s Inheritance Bicycle class • Many different bicycles Bicycle • Classic case for inheritance • Base-class of Bicycle, from which specialized Bicycle classes inherit Road Mountain Child Bicycle Bicycle Bicycle 7 8 Bicycle class UML Notation Class Name Attribute Aggregation Attribute Operation Operation Inheritance Composition • UML Representation for a Class • UML stands for Unified Modeling Language 9 10 Bicycle class Inheritance Bicycle class Inheritance // source file name bicycle.java public abstract class bicycle{ private int gear; Bicycle Superclass private boolean front_brake; private boolean rear_brake; public void setGear(int newValue); public void getMaximumSpeed(); Road Mountain Child … Subclasses Bicycle Bicycle Bicycle } public class road_bicycle extends bicycle{ … } • Abstract classes: cannot be instantiated. public class mountain_bicycle extends bicycle{ • Abstract methods: without an implementation. … } 11 12 2

  3. 10/26/2011 Inheritance summary Bicycles Simulator v2 • A class inherits fields and methods from all its • More features of bicycles superclasses, whether direct or indirect . A subclass can override methods that it inherits, or it can hide fields or methods that it inherits. • An abstract class can only be subclassed; it cannot be instantiated. An abstract class can contain abstract methods. • You can prevent a class from being subclassed by using the final keyword in the class's declaration. Similarly, you can prevent a method from being – Foldable overridden by declaring it as a final method. – With motor 13 14 Bicycles Simulator v2 Bicycles Simulator v2 • Some features are not appropriate for all public abstract class bicycle{ subclasses of Bicycle. … • If those features are implemented in the public void setGear(int newValue); methods of superclass, subclasses inherit public void setFold(boolean newState ); inappropriate behaviour. public void setMotor(double newSpeed); • Need to override the methods. … • Is Inheritance the right model here? } 15 16 Bicycle Inheritance Interface • Disabling operations on derived classes • Does the behaviour belong in the • Maintenance problem baseclass in the first place? • Put it in an interface – Every new bicycle subclass will require you to consider overriding setFold()/setMotor() • Interfaces are a collection of abstract – Danger of not overriding methods on new methods that an Object implements bicycles… • Object can support multiple interfaces (no multiple inheritance!) 17 18 3

  4. 10/26/2011 Object Interface Usage of interfaces interface foldable { • Client can ask an object if it supports an void setFold(boolean newState); interface. } interface with_motor { • If it does it can use the interface, if not try void setMotor(double newSpeed); } something else. class myBike1 extends bicycle implements foldable { • Interfaces are declarations, they contain public void setFold(boolean newState){ …} … no code to implement methods. } class myBike2 extends bicycle implements foldable, with_motor { … } 19 20 Bicycle class hierarchy Duplicate Code • Interfaces have no code • Each bicycle subclass must have its own implementation for each interface. • Any change to an implementation must be made to every sub-class that supports it 21 22 Adapter Adapter • The intent of Adapter is to provide the ExistingClass <<interface>> interface that a client expects while using UsefulMethod() RequiredMethod() a existing class. • A new subclass of Bicycle: Bicycle_without_pedals NewClass interface no_pedal { void setNoPedal(); RequiredMethod() } class myBike1 extends bicycle implements • When a developer of client code thoughtfully defines the client‘s no_pedal { … needs, you may be able to fulfill the interface by adapting existing } code. 23 24 4

  5. 10/26/2011 Object Adapter Object Adapter example ExistingClass RequiredClass RequiredMethod() UsefulMethod() NewClass RequiredMethod() • ExistingClass is instantiated in NewClass so that UsefulMethod can be used. It can be dangerous if you don‘t override all the methods that might be called. 25 26 Adapter summary Change • The Adapter pattern lets you use an • Change is the one constant in software existing class to meet new requirements. development • Class adapter: create new class that • Don‘t make rigid designs implements new interface and subclasses • Changing something should be easy and an existing class. require the least amount of effort • Object adapter: create a new client subclass that uses an instance of the existing class. 27 28 Design Principle Design Principle • Some parts of the application are varying with new requirements, others don‘t “Identify the aspects of your application that vary and separate them from what • Encapsulate the bits that change into a stays the same” new object so that it can be changed easily • This is at the heart of every design pattern 29 30 5

  6. 10/26/2011 Changing Bicycles Bicycle (re)design • Thought we had a good design for our • Bicycle class seems to work bicycle simulator – Apart from methods e.g. setFold() • Separate these methods off into new • But changing features may require major classes or interfaces changes – Foldable behaviour • How do we make it a good design? – With Moter behaviour – Without Pedal behaviour – ... 31 32 Bicycle Behaviour Design Principle • Keep things flexible • Instances of Bicycle are assigned behaviours ―Program to an interface, not an • Can we change a behaviour dynamically? implementation‖ – To make a foldable bicycle non-foldable? • Mutators to change Bicycle‘s behaviour at runtime Mutators: setter() methods 33 34 Program to an interface Behaviour Interfaces Interface A{ method()… }; • FoldableBehaviour and Class B implement A { method()...}; WithMotorBehaviour // program 1: // program 2: • Gives us flexibility Class X { Class X { – Don‘t inherit any implementation private A a1; private B b1; public void useA (A b1){ public void useB(){ – Bicycle‘s aren‘t tied to an implementation a1 = b1; b1.method(); a1.method(); } } 35 36 6

  7. 10/26/2011 Integrating Behaviours <<interface>> foldable • Interface type — don‘t want to bind this to setFold() an implementation • Add instance variables for the behaviours – FoldableBehaviour – WithMotorBehaviour FoldableBicycle Non-foldableBicycle setFold() { setFold() { – … /* Fold the bike */ /* Do nothing */ } } • Add methods to call the behaviour 37 38 What is happening? public abstract class Bicycle { protected FoldableBehaviour fordable; • When myBike is created: protected WithMotorBehaviour with_motor; … – Creates objects for correct behaviours } – Sets variables to instantiate existing classes public class myBike extends Bicycle (interfaces) { public FoldableBehaviour getFordable { • When setFoldable() called, setFold() is return this.fordable;} called on the newly created object public void setFordable(FoldableBehaviour state) { fordable = state.setFold(); }; • Equivalent for setMotor()… … } 39 40 Exercise Strategy Pattern interface Monster { void menace();} interface DangerousMonster extends Monster { void destroy();} • Example of the ‗Strategy‘ Pattern interface Lethal { void kill();} class Zombie implements DangerousMonster { public void menace() {// some code here } • Strategy Pattern defines a family of public void destroy() {// some code here } } algorithms, encapsulates each one, and interface Vampire extends DangerousMonster, Lethal { void drinkBlood();} makes them interchangeable. class VeryBadVampire implements Vampire { public void menace() {// some code here } public void destroy() {// some code here } • Strategy lets the algorithm vary public void kill() {// some code here } public void drinkBlood() {// some code here } } independently from clients that use it ** You need create three new classes: Monster1: is a zombie and has kill() method Monster2: has the methods of kill(), destroy(), and a new method fly() Monster3: is a VeryBadVampire but does not have kill() method 41 42 7

  8. 10/26/2011 Reading • ErichGamma, RichardHelm, RalphJohnson, and JohnVlissides (the Gang Of Four), Design Patterns: Elements of Reusable Object-Oriented Software , Addison Wesley Professional, 1994 • Steven J. Metsker and William C. Wake, Design Patterns in Java, Addison Wesley, 2006 • http://www.javacamp.org/designPattern/ 43 8

Recommend


More recommend