Design Patterns Lecture 2 Josef Hallberg josef.hallberg@ltu.se 1 Patterns covered Creational Abstract Factory, Builder, Factory Method, Prototype, Singleton Structural Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy Behavioral Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor 2 1
Structural Patterns How classes and objects are composed to form a larger structure Structural Class patterns Uses inheritance to compose interfaces or implementations Structural Object patterns describes ways to compose objects to realize new functionality Adapter, Bridge, Composite, Decorator, Facade, Flyweight, Proxy 3 Adapter Problem/Applicability Interface mismatch Create a reusable class that cooperates with unrelated or unforeseen classes 4 2
Adapter Solution Class Adapter Client Target + Request() Adaptee + SpecificRequest() SpecificRequest(); Adapter + Request() 5 Adapter Solution Object Adapter Client Target +Request() Adaptee + SpecificRequest() adaptee->specificrequest(); Adapter +Request() (adaptee) 6 3
Adapter -- example Bought a new positioning system Code included but interfaces mismatch Make an adapter to include the new positioning system into our platform 7 Adapter Example public interface PullPositionDevice { public Coordinate getposition(); } 8 4
Adapter Example public interface PullPositionDevice { public Coordinate getposition(); } public class YPositionDevice extends YPosition implements PullPositionDevice { } public Coordinate getposition() { String position = super.positionrequest(); Coordinate c = //transform String to Coordinate return c; } 9 Adapter Example public interface PullPositionDevice { public Coordinate getposition(); } public class YPositionDevice implements PullPositionDevice { private YPosition yposition; } public Coordinate getposition() { String position = yposition.positionrequest(); Coordinate c = // transform String to Coordinate return c; } 10 5
Class adapter Consequences Adapts Adoptee to Target by committing to a concrete adapter class Lets Adapter override some of Adaptee s behavior Can still act as the original Type if necessary Object Adapter Lets a single Adapter work with many Adaptees Makes it harder to override Adaptee behavior Can not act as the original Type 11 Bridge -- Problem Class with some parts consisting of general code some parts have several different implementations Could use inheritance put the general code in each subclass might not be flexible enough 12 6
Bridge Solution Decouple the code General code Several different implementations The Bridge pattern decouples an abstraction from its implementation so that the two can vary independently 13 Bridge -- UML Abstraction + Operation() Implementor + OperationImp() Imp->OperationImp() RefinedAbstraction ConcreteImlementorA + OperationImp() ConcreteImlementorB + OperationImp() 14 7
Bridge example Application to run on a desktop computer as well as a mobile phone Screen size varies Input capabilities vary Instead of making two different applications we can make a bridge to the device specific implementations 15 Bridge example cont. A1. public class Abstraction { A2. A3. public void close(){ A4. System.exit(0); A5. } A6. public void open() { A7. // do cool open stuff A8. } A9. public void undo() { A10. // undo stuff A11. } A12. A13. public void operationx() { A14. imp = getimp(); A15. imp->operationx(); A16. } A17. } C1. public interface Implementor { C2. public void operationximpl(); C3. } D1. public class ConcreteImplA D2. implements Implementor D3. { D4. public void operationximpl() D5. { D6. // Do things D7. } D8. } E1. public class ConcreteImplB E2. implements Implementor E3. { E4. public void operationximpl() E5. { E6. // Do other things E7. } E8. } 16 8
Bridge -- usage Consequences Decoupling interface and implementation Improved extensibility Hiding implementation details from clients 17 Composite -- Problem Structured design composed of several graphical objects Could implement in a single class Larger designs will be hard to read it will be less flexible 18 9
Composite Solution Compose objects into a tree structure with composites and leaves acomposite for all children execute operation aleaf aleaf acomposite aleaf aleaf aleaf aleaf 19 Composite Solution cont. In Java AWT there is a similar pattern for graphic objects. java.awt.container java.awt.component Component Container Button TextArea Label Window Panel Frame Dialog 20 10
Composite -- UML Client Component + Operation() + Add(Component) + Remove(Component) + GetChild(int) : Component Leaf + Operation() Component + Operation() + Add(Component) + Remove(Component) + GetChild(int) : Component children forall g in children g.operation(); 21 Composite -- example Map application map as background A dot (your position) A scale marker Scale marker could be a composite in itself (line and text) When the map is redrawn it also lets all its children redraw 22 11
Composite example cont. A1. public abstract class MapObject { A2. protected boolean visible; A3. public void setvisible(boolean see) { A4. this.visible = see; A5. } A6. public abstract void paint(graphics g); A7. } B1. public class MapCompass extends MapObject { B2. public void paint(graphics g) { B3. if (g!=null) { B4. if(visible) { B5. // paint the compass B6. } } } } C1. public class MapPosition extends MapObject { C2. public void paint(graphics g) { C3. if (g!=null) { C4. if(visible) { C5. // paint the dot showing the position C6. } } } } 23 Composite example cont.2. 1. public class MapCanvas extends Canvas implements MapObject, Component 2. { 3. //... 4. //... 5. public void addmapobject(mapobject mo) { 6. children.addelement(mo); 7. } 8. 9. public void paint(graphics g) { 10. // paint itself 11. for(int i=0; i<children.size(); i++) { 12. ((MapObject)children.elementAt(i)).paint(aGraphicsBuffer); 13. } 14. } 15. 16. //... 17. //... 18.} 24 12
Composite -- usage Consequences Defines class hierarchies consisting of primitive objects and composite objects Makes the client simple Makes it easier to add new kinds of components 25 Let s take a break! =) 26 13
Façade Problem/Applicability You want to provide a uniform interface to a set of interfaces in a subsystem You want to make a subsystem easier to use There are many dependencies between clients and subsystems 27 Façade Problem/Applicability Client1 Client2 Client3 Client4 subsystem classes 28 14
Façade Solution Client1 Client2 Client3 Client4 subsystem classes Facade 29 Facade Example A1. public class Client1 { A2. FacadeClass1 c1; A3 FacadeClass2 c2; A4.... A5. A6. public void operation() { A7. c1.operation1(); A8. c2.operation2(); A9.... A10. } A11. } B1. public class Client1 { B2. Facade facade; B3. B4. public void operation() { B5. facade.facadeop1(); B6. facade.facadeop2(); B7... B8. } OR C1. public void operation() { C2. facade.facadeop(); C3. } C4. } 30 15
Façade Consequences Shields clients from subsystem components Promotes weak coupling between subsystem and client Doesn t prevent use of subsystem classes if needed 31 Summary - structural Adapter Lets classes with incompatible interfaces work together Bridge Decouple an abstraction from its implementation so that the two can vary independently Composite Lets clients treat individual objects and compositions of objects uniformly Facade Provide a unified interface to a set of interfaces in a subsystem 32 16
Behavioural patterns Concerned with algorithms and assignment of responsibilities. Complex control-flow that s hard to follow at run-time class: use inheritance to distribute behaviour between classes object: object composition to, for example, describe how a group of objects should cooperate 33 Chain of Responsibility Problem You want to avoid coupling the sender of a request with a certain receiver More than one object may handle a request and the handler isn t known beforehand The set of objects that can handle a request should be specified dynamically 34 17
Chain of Responsibility Solution Client Handler successor +handlerequest() : void ConcreteHandler1 +handlerequest(): void ConcreteHandler2 +handlerequest(): void 35 Chain of Responsibility Solution Client HelpHandler +handlehelp() : void handler handler->handlehelp() Application +handlehelp(): void Dialog Widget +handlehelp(): void Button +handlehelp(): void -showhelp(): void if can handle { showhelp(); } else { Handler::handleHelp(); } 36 18
Chain of Responsibility Consequences Reduced coupling Added flexibility in assigning responsibilities to objects Receipt isn t guaranteed 37 Iterator Problem/Applicability You wish to create an aggregated object Access the elements sequentially Don t want to expose underlying representation Want to support multiple types of traversals Remember state 38 19
Iterator Solution Aggregate + createiterator() Iterator + first() + next() + isdone() + currentitem() ConcreteAggregate + createiterator() return new ConcreteIterator(this) ConcreteIterator + first() + next() + isdone() + currentitem() 39 Iterator -- example 40 20
Iterator Example 1. public class Client { 2. private Aggregate agg; 3. 4. public void setaggregate(aggregate agg) { 5. this.agg = agg; 6. } 7. 8. public void print() { 9. Iterator iterator = this.agg.createiterator(); 10. while (!iterator.isdone()) { 11. System.out.println(iterator.currentItem()); 12. iterator.next(); 13. } 14.} 15.} 41 Iterator Consequences It supports variations in the traversal of an aggregate Iterators simplify the Aggregate interface More than one traversal can be pending on an aggregate Remembers its own state 42 21
Iterator Implementation Issues Who controls the iteration? Who defines the traversal algorithm? How robust is the iterator? Additional Iterator operations 43 Summary - behavioral Chain of Responsibility Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Iterator Provide a way to access the elements of an aggregate object sequentially 44 22
Questions? 45 23