4da5ac9e0ad374b0a4986216be000ddd.ppt
- Количество слайдов: 135
Design Patterns Introduction and Examples in Java Mask slides 9 -10 -11 and 76 -77 before printing Unmask them for presentation Always mask slide 1 (this one)
Design Patterns Introduction and Examples in Java (V 1. 2) Jean-Paul Rigault Professor University of Nice Sophia Antipolis Polytechnic Engineering School Department of Computer Science Email: jpr@essi. fr
Contents n Motivation n The universal Design Patterns (from the Go. F Book) n n n With a simple example Characterization of Design Patterns Classification Examples of implementation in Java References 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 3
Some preliminary remarks n The class is too small as a reusability unit n n Cooperation between several classes/instances Code is not the only item that can be reused n n Reusing analysis, design Reusing (micro-)architectures recurrently found in design 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 4
Introduction to Design Patterns Motivation, Characterization
Motivation for Design Patterns A Simple Example instr : : = simple_instr | block : : = instr* simple_instr : : = assignment | selection. . . 19/03/2018© Jean-Paul Rigault, 20002005 Method propagation Instr exec() * exec Block Simple. Instr exec() Assignment exec() (1) Selection . . . exec() Design Patterns: Introduction and Examples in C++ 6
Motivation for Design Patterns A Simple Example n (2) Figure Graphic editor n Grouping/Degroupin g move() * move Simple. Fig Group move() Rectangle move() 19/03/2018© Jean-Paul Rigault, 20002005 Triangle . . . move() Design Patterns: Introduction and Examples in C++ 7
Motivation for Design Patterns A Simple Example n (3) Circuit VLSI CAD simul() a sum b * simul carry Half-adder Simple. Gate Operator simul() And. Gate simul() 19/03/2018© Jean-Paul Rigault, 20002005 Inverter . . . simul() Design Patterns: Introduction and Examples in C++ 8
Motivation for Design Patterns A Simple Example (3) Objet op() Simple_Obj * op Composite op() Obj_Var 1 op() 19/03/2018© Jean-Paul Rigault, 20002005 Obj_Var 2 . . . op() Design Patterns: Introduction and Examples in C++ 9
Motivation for Design Patterns A Simple Example (3) Instr exec() * exec Simple_Instr Assignment exec() 19/03/2018© Jean-Paul Rigault, 20002005 Block Selection . . . exec() Design Patterns: Introduction and Examples in C++ 10
Motivation for Design Patterns A Simple Example (3) Objet op() Simple_Obj * op Composite op() Obj_Var 1 op() 19/03/2018© Jean-Paul Rigault, 20002005 Obj_Var 2 . . . op() Design Patterns: Introduction and Examples in C++ 11
Motivation for Design Patterns A Simple Example (3) Figure move() * move Simple_Fig Group move() Rectangle move() 19/03/2018© Jean-Paul Rigault, 20002005 Triangle . . . move() Design Patterns: Introduction and Examples in C++ 12
Motivation for Design Patterns A Simple Example (3) Objet op() Simple_Obj * op Composite op() Obj_Var 1 op() 19/03/2018© Jean-Paul Rigault, 20002005 Obj_Var 2 . . . op() Design Patterns: Introduction and Examples in C++ 13
Motivation for Design Patterns A Simple Example (3) Circuit simul() Simple_Gate * simul Operator simul() And_Gate simul() 19/03/2018© Jean-Paul Rigault, 20002005 Inverter . . . simul() Design Patterns: Introduction and Examples in C++ 14
Motivation for Design Patterns A Simple Example n Objet The Composite pattern n (4) op() Recursive aggregation Uniform Simple_Obj processing of simple objects and composite ones Obj_Var 1 Obj_Var 2 Method propagation op() 19/03/2018© Jean-Paul Rigault, 20002005 * op Composite op() . . . op() Design Patterns: Introduction and Examples in C++ 15
Motivation for Design Patterns A Simple Example (5) g 3: Group n The Composite pattern n Tree like data structure t 1 r 2 r 1 g 3 r 3 t 1: Triangle r 2: Rectangle r 1: Rectangle r 3: Rectangle c 1 g 1 e 1 g 1: Group c 1: Circle g 2: Group g 2 e 1: Ellipse t 2: Triangle 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 16
Motivation for Design Patterns A Simple Example n Design Patterns: reusable micro-architectures n n n Appear recurrently in design Involve several classes/objects The class is not the ultimate reuse unit Non reducible to library code n n (6) Recoding is needed for each application context Identify, name, characterize, evaluate… design patterns The Go. F book n 23 universal (fundamental) design patterns 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 17
Design Patterns From Idioms to Frameworks (1) Design Patterns Toolkits (libraries) Idioms Language dependency Frameworks Application dependency Application programs Languages 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 18
Design Patterns From Idioms to Frameworks n Idioms n n n (2) Reusable tricks (or traits, or micro-architectures…) Specific to a given programming language Examples n n n Code sharing by private inheritance (C++) Delegation through operator-> (C++) “Resource acquisition is initialization” (C++) Nested classes (Java) Anonymous classes (Java) Immutable classes (Java)… 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 19
Design Patterns Frameworks and Librairies Librar y General Application specific code purpose code Framewor k Application specific code skeleton main 19/03/2018© Jean-Paul Rigault, 20002003 main Design Patterns: Introduction and Examples in Java 20
Design Patterns Characterization n n Name Intention n Motivation Applicability n n Structure n n Participants Collaboration 19/03/2018© Jean-Paul Rigault, 20002003 Consequences Example of implementation n n Advantages Drawbacks Language-dependent Similar patterns Design Patterns: Introduction and Examples in Java 21
Design Patterns Characterization: Composite Pattern (1) n Name n n Composite op() Intention n Object Recursive aggregation Simple. Obj Uniform processing of simple objects and composite ones Structure n UML diagram 19/03/2018© Jean-Paul Rigault, 20002003 Obj. Var 1 op() Obj. Var 2 op() Design Patterns: Introduction and Examples in Java * op Composite op() . . . 22
Design Patterns Characterization: Composite Pattern (2) n Consequences n n n o Homogeneous manipulation of simple and composite objects (expected) Simplification of clients Extensibility: easy to add new components (simple or composite) Sometimes too general o Difficult to restraint the composition for a group of objects 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 23
Design Patterns Characterization: Composite Pattern (3) n Example of implementation (Figure in Java) public abstract class Figure { // or an interface public abstract void move(ind dx, int dy); } class Group extends Figure { Vector
Design Patterns Conventions for UML Diagrams UML and Java: an interface UML: an operation signature Java: a method signature <
The Go. F Book Universal Design Patterns Overview
Design Patterns The Go. F Book Patterns (1) Design Patterns: Elements of Reusable Object-Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides (the so-called “Gang of Four Book”, the Go. F book) Addison Wesley, 1995 n 23 “universal” design patterns n n Creation patterns (5) Structural patterns (7) Behavioral patterns (11) Many application context specific patterns have been defined by other authors 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 27
Design Patterns The Go. F Book Patterns n Creation patterns n n n Abstract the creation of objects Make code independent from the exact type of created objects Ensure type homogeneity during creation 19/03/2018© Jean-Paul Rigault, 20002003 n n n (2) Abstract Factory Builder Prototype Singleton Factory Method (Virtual Constructor) Design Patterns: Introduction and Examples in Java 28
Design Patterns The Go. F Book Patterns n Structural patterns n n n Make code independent from (internal) structural variations of objects Avoid explosion of class number as implied by (multiple) inheritance Separate implementation from specification 19/03/2018© Jean-Paul Rigault, 20002003 n n n n (3) Adapter (Wrapper) Bridge (Handle/Body) Composite Decorator Facade Flyweight Proxy (Surrogate) Design Patterns: Introduction and Examples in Java 29
Design Patterns The Go. F Book Patterns n Behavioral patterns n n n Reified algorithms Assignment and separation of responsibilities during some process Communication between complex objects n n n 19/03/2018© Jean-Paul Rigault, 20002003 (4) Chain of Responsibility Command Interpretor Iterator Mediator Memento Observer State Strategy Template Method Visitor Design Patterns: Introduction and Examples in Java 30
The Go. F Book Universal Design Patterns Creation Patterns
Creation Patterns n n n Abstract Factory Builder Prototype n n n Duplicating objects in Java Singleton Factory Method (Virtual Constructor) n Extensible implementation of Factory Method 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 32
Creation Patterns Abstract Factory (1) Window w = new Mac. Window(. . . ); Button b = new Mac. Button(. . . ); Scroll. Bar sb = new Mac. Scroll. Bar(. . . ); n Rigid (built-in) type dependency n n n Changing interface style is difficult Adding a new interface style is difficult How to guarantee interface style consistency? 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 33
Creation Patterns Abstract Factory (2) Window Widget. Factory Catalog create. Window() of productscreate. Button() Mac. Window create. Scroll. Bar() Button Mac. Button Motif. Widget. Fact create. Window() create. Button() create. Scroll. Bar() Motif. Button Mac. Widget. Fact create. Window() create. Button() create. Scroll. Bar() Motif. Window 19/03/2018© Jean-Paul Rigault, 20002003 Scroll. Bar Mac. Scroll. Bar Motif. Scroll. Bar Mac family Motif family Design Patterns: Introduction and Examples in Java 34
Creation Patterns Abstract Factory n (3) Creation of the factory itself Widget. Factory factory = new Mac. Widget. Factory(); n Creation of objects n Just order from the factory Window w = factory. create. Window(. . . ); Button b = factory. create. Button(. . . ); Scroll. Bar sb = factory. create. Scroll. Bar(. . . ); 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 35
Creation Patterns Abstract Factory n (4) Applicability n n The system must be independent of the way the objects are created, composed, or represented The objects must be classified into families of products The families must be exclusive The interface of a product must not depend on the family it belongs to 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 36
Creation Patterns Abstract Factory n Consequences n n Abstraction of the object creation process It is easy to change or add a family of products n n o Even dynamically! Consistency within a given family is enforced Introducing a new product is not easy o n (5) Static list of all products in the abstract factory Related patterns n Singleton, Factory Method, Builder 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 37
Creation Patterns Builder Director (1) Builder construct() build. Part. A() build. Part. B(). . . for all subparts build the subpart Separate the construction of a complex object from its representation so that the same construction process can create different representations. 19/03/2018© Jean-Paul Rigault, 20002003 Concrete. Builder build. Part. A() build. Part. B(). . . get. Result() Design Patterns: Introduction and Examples in Java Other Concrete. Builder Product 38
Creation Patterns Builder (2) : Client : Concrete Builder : Director construct() build. Part. A() build. Part. B() build. Part. C() get. Result() 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 39
Creation Patterns Builder (3) joe: Client an. Architect: Director build. House() Bouyges: Concrete. Builder do. Earthwork() lay. Foundations() build. Walls() do. Internal. Work() get. House() 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 40
Creation Patterns Builder n Consequences n Separation between construction and internal representation n (4) The internal representation and the construction process may vary independently Fine control over the construction process Related patterns n n Abstract Factory (one shot construction) Composite (usually a Builder constructs a Composite) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 41
Creation Patterns Prototype n (1) Intention n n Creation of a object as a duplication (clone) of another object The exact type of the duplicated object is unknown (only a supertype is known) n Thus a kind of polymorphic copy Some. Type an. Object; . . . Some. Type another. Object = an. Object. duplicate(); 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 42
Creation Patterns Prototype n (2) Implementation in Java: using clone() n clone() is a (protected) method of class Object o Its default implementation is hardly suitable n n Interface Cloneable does not declare clone()! The contract of clone() is not precise enough n n n The meaning of “copy” depends on the class of the object Different objects: x. clone() != x ? Type: x. clone(). get. Class()== x. get. Class()? Equality: x. clone(). equals(x)? Interaction with constructors is dubious See Effective Java (Item 10) for details… 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 43
Creation Patterns Prototype n (3) Implementation in Java: using a Copy Constructor n A C++-like approach! Safer than clone() public abstract class Some. Type { // or interface public abstract Some. Type duplicate(); //. . . } public class Some. Sub. Type extends Some. Type { public Some. Sub. Type(Some. Sub. Type a) {. . . } public Some. Type duplicate() { return new Some. Sub. Type(this); } } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 44
Creation Patterns Prototype n (4) Implementation in Java: deep copy using serialization public class Some. Object implements Cloneable { public final Some. Object clone() { Byte. Array. Output. Stream b. Out = new Byte. Array. Output. Stream(); Object. Output. Stream out = new Object. Output. Stream(b. Out); out. write. Object(this); out. close(); Object. Input. Stream in = new Object. Input. Stream( new Byte. Array. Input. Stream(b. Out. to. Byte. Array())); Some. Object obj = (Some. Object) in. read. Object(); return obj; 19/03/2018© Jean-Paul Rigault, 20002003 } Design Patterns: Introduction and Examples in Java 45
Creation Patterns Prototype n (5) Consequences n n Abstraction of the creation process (like Abstract Factory and Builder) It is possible to add and remove products dynamically (simply by registering prototypes dynamically) Reuse objects which are complex to build A fundamental pattern in languages like C++ where classes are not objects n n Replace the class by one of its instance, a prototypal instance Even useful in Java, in combination with reflection 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 46
Creation Patterns Singleton n A class with a unique instance n n n A useful concept (but a useless pattern? ) One printer spooler, one window manager in a system, one factory… More delicate that it may seem. . n n Creation/allocation? Destruction/lifetime? Dangling reference? Polymorphism? Interaction with class derivation? Interaction with multithreading? See Andrei Alexandrescu (Modern C++ Design) for an interesting discussion (which goes beyond C++) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 47
Creation Patterns Singleton: a Simple Implementation public class Singleton { public static Singleton the. Instance() { return _instance; } protected Singleton() {. . . } protected static Singleton _instance = new Singleton(); . . . n n n The protected constructor allow subclassing The protected _instance can be overriden by derived classes Note that singleton are seldom explicit; they may simply appear as class static variables } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 48
Creation Patterns Factory Method (Virtual Constructor) n Problems with Abstract Factory: extensibility n n Difficult to add a new product The type of the object is imposed from outside File of figures Figure pf; Rectangle Ellipse pf = the first figure in the file? Square a. Ellipse a. Circle a. Square … Circle 19/03/2018© Jean-Paul Rigault, 20002003 a. Circle a. Rectangle Design Patterns: Introduction and Examples in Java 49
Creation Patterns Factory Method implementation (1) n Using an ordinary constructor? n n It must be a constructor of Figure The call to a constructor imposes the type of the object (a constructor cannot be virtual in C++, as well as it is not dynamically bound in Java) Moreover Figure is usually an abstract class! Using (a redefinition of) operator new (in C++)? n n Which size to allocate? new cannot be virtual since it is static Moreover, which constructor to call after new? Impossible in Java… 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 50
Creation Patterns Factory Method implementation (2) n Using a static scheme? public class Figure { public static Figure create(. . . ) { Type. Tag type =. . . ; // read from file. . . switch (type) { case RECTANGLE: // read Rectangle attributes from the file return new Rectangle(. . . ); case SQUARE: // read Square attributes from the file return new Square(. . . ); . . . } } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 51
Creation Patterns Factory Method implementation (3) n Towards an extensible scheme n n The base class should have no static knowledge about its derived classes Instances should be constructed through their class constructor n n Thus, only a derived class knows how to construct its instances n n Indeed the constructors may have side-effects of interest. . . So we need a method to delegate object creation to subclasses It should be possible to add derived classes without 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 52
Creation Patterns Factory Method pattern (1) Creator factory. Method() Product Concrete. Creator factory. Method() <
Creation Patterns Factory Method pattern Figure n create() factory. Method() (2) The Product and the Creator hierarchies may be (and often are) identical n Rectangle factory. Method() Ellipse factory. Method() The create() static method dispatches the creation to the adequate factory. Method() return new Rectangle(. . . ) return new Ellipse(. . . ) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 54
Creation Patterns Extensible Factory Method n An extensible scheme to construct an object 1. 2. 3. 4. n (1) Get the type tag of the object (reading from a file, deserializing, XML tag…) Find out which class corresponds to the tag Obtain (dynamically) an object of the corresponding type Invoke the Factory Method through this “exemplar” or “prototype” object Steps 2 and 3 are the key n either use a map
Creation Patterns Extensible Factory Method n (2) Example using Java Class. for. Name() public class Figure { public static final String PACKAGE = "fr. unice. polytech. jpr. figures. "; } public static Figure create(. . . ) { // 1. Read the type tag (from the file…) String tag =. . . ; // 2. Compute the full class name String name = PACKAGE + tag; // 3. Obtain an exemplar of this type Figure fig = (Figure) Class. for. Name(name). new. Instance(); // 4. Call Factory Method to create the instance return fig. factory. Method(. . . ); }. . . 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 56
Creation Patterns Extensible Factory Method n (3) Example using Java Class. for. Name() (cont. ) public class Rectangle extends Figure { public Rectangle factory. Method(. . . ) { // Read Rectangle attributes (from the file…) attributes =. . . ; // Construct a new Rectangle return new Rectangle(attributes); }. . . } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 57
Creation Patterns Extensible Factory Method n (4) Other implementations of Factory Method in Java n n Defining an ad hoc Class. Loader Using serialization/deserialization n n read. Object() is indeed a kind of virtual constructor However, a constructor is not invoked to initialize the object! 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 58
The Go. F Book Universal Design Patterns Structural Patterns
Structural Patterns n n n n n Adapter (Wrapper) Bridge (Handle/Body) Proxy (Ambassador, Surrogate) Adapter, Bridge, and Proxy Composite Decorator Composite and Decorator Facade Flyweight 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 60
Structural Patterns Adapter (Wrapper) n (1) Intent n n Adapt a class interface so that the application may use it Separate the application API from a toolkit/library API Client Application 19/03/2018© Jean-Paul Rigault, 20002003 Adaptation Toolkit class appli_interface tool_interface Design Patterns: Introduction and Examples in Java 61
Structural Patterns Adapter (Wrapper) n (2) Adaptation using inheritance (Class Adapter) target adaptee Stack Client push() pop() adapter Stack. Vector push() pop() 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java My. Vector get(int i) delegate to get() 62
Structural Patterns Adapter (Wrapper) n (3) Adaptation using composition (Object Adapter) target Stack Client adaptee My. Vector push() pop() adapter Stack. Vector push() pop() 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java vec get(int i) delegate to vec. get() 63
Structural Patterns Adapter (Wrapper) n Class adapter n Adaptation through “multiple” inheritance n n o o Only one adapter/adaptee object, no indirection Code sharing through “implementation” inheritance n n (4) Easy to override adaptee behavior Explosion of the number of derived (adapter) classes if the adaptee is the head of a class hierarchy No private inheritance in Java: risk of breaking consistency Object adapter Adaptation through (reference) composition n If the adaptee is the head of a class hierarchy, polymorphism can be used 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and o Access through indirection Examples in Java n 64
Structural Patterns Adapter (Wrapper) n (5) Special case of Adapter: merging hierarchies Figure Image fig img Ellipse Pict. Image draw() Rectangle paint() Jpeg. Image Tiff. Image Square Circle fig. draw() 19/03/2018© Jean-Paul Rigault, 20002003 Clipped. Image draw() paint() Design Patterns: Introduction and Examples in Java img. paint() 65
Structural Patterns Bridge (Handle/Body) n (1) Intent n Decouple an abstraction (interface) from its implementation so that both may vary independently Interface op 1() op 2 (). . . 19/03/2018© Jean-Paul Rigault, 20002003 impl. Implementation Each operation is delegated to one (or a combination of) operation(s) of the implementation Design Patterns: Introduction and Examples in Java impl. Op 1() impl. Op 2 (). . . 66
Structural Patterns Bridge (Handle/Body) n Using multiple inheritance? n Window Explosion of the number of derived classes Dialog. Window redraw() raise() lower() iconify() deiconify() draw. Line() draw. Text(). . . Applic. Window Icon. Window 19/03/2018© Jean-Paul Rigault, 20002003 (2) Mac. Window XWindow Design Patterns: Introduction and Examples in Java Win 32 Window 67
Structural Patterns Bridge (Handle/Body) impl Window redraw() raise(). . . Dialog. Window (3) Impl. Window redraw() raise(). . . Applic. Window Icon. Window 19/03/2018© Jean-Paul Rigault, 20002003 XWindow Win 32 Window Mac. Window Design Patterns: Introduction and Examples in Java 68
Structural Patterns Bridge (Handle/Body) n (4) How to select a particular windowing system? n Through an Abstract factory, of course! public interface Window. System. Factory { public Window. Impl create. Window. Impl(); public Color. Impl create. Color. Impl(); public Font. Impl create. Font. Impl(); . . . } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 69
Structural Patterns Bridge (Handle/Body) n (5) Consequences n Decouple interface from implementation n n Improve extensibility n n Eliminate compile-time dependencies Allow run-time configuration or even change of implementation Better structure “The key to extensibility is indirection” Hide implementation details n Avoid private members from being visible (opaque types) Adapt the interface Introduction and Examples in Java Design Patterns: 19/03/2018© Jean-Paul Rigault, 2000 n 2003 70
Structural Patterns Proxy (Surrogate, Ambassador) (1) n Intent n Controlling the access to an object through a surrogate object Some. Object op 1() op 2(). . . Real. Object real op 1() op 2(). . . 19/03/2018© Jean-Paul Rigault, 20002003 real. op 1() Proxy. Object op 1() op 2(). . . Design Patterns: Introduction and Examples in Java real. op 2() 71
Structural Patterns Proxy (Surrogate, Ambassador) (2) n Types of proxies n Remote proxy (Ambassador) n n Virtual proxy n n n A local representative for an object in a different address space (possibly on a remote machine) Create expensive object on demand Similar to virtual memory handling Protection proxy (Body Guard) n Handle access rights to an object 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 72
Structural Patterns Proxy (Surrogate, Ambassador) (3) n Types of proxies (cont. ) n Smart reference (Smart Pointer) n n Replacement for a pointer, with additional behavior Reference counting (sharing objects) Multi-threads synchronization Loading on demand (see Virtual Proxy) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 73
Structural Patterns Adapter, Bridge, Proxy n Related patterns with similar Some. Object structure n n n (1) Indirect access through an intermediary object Interface_1 Intents are different Interfaces are different n n n Adapter n Interface_1 Interface_2 Proxy n Interface_1 Interface_2 Bridge n Both are possible… n Separate specification/body 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java obj Another. Object Interface_2 74
Structural Patterns Composite n n See the Introduction The Composite pattern n n Recursive aggregation Uniform processing of simple objects and composite ones 19/03/2018© Jean-Paul Rigault, 20002003 Object op() Simple. Obj * op Composite op() Obj. Var 1 op() Obj. Var 2 op() Design Patterns: Introduction and Examples in Java . . . 75
Structural Patterns Decorator n Intent n n n (1) Attach responsibilities to an object dynamically Avoid explosion of class number due to (multiple) inheritance Example title bar border still a window vertical scroller application window horizontal scroller 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 76
Structural Patterns Decorator n (2) Example (cont. ) n Using multiple inheritance? Window. With. HScroll Window. With. VScroll Window. With. HVScroll Window. With. Title Window. With. Border Window. With. Title_Border Window. With. Border. And. Title 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 77
Structural Patterns Decorator n Window Example (cont. ) n (3) Using the Decorator pattern other sorts of windows undecorated. redraw() undecorated 1 Decorated. Window redraw() Window. With. Title Window. With. Border Window. With. HScroll redraw() draw. Title() redraw() draw. Border() redraw() draw. HScroll() super. redraw(); draw. Title() 19/03/2018© Jean-Paul Rigault, 20002003 super. redraw(); draw. Border() super. redraw(); draw. HScroll() Design Patterns: Introduction and Examples in Java 78
Structural Patterns Decorator class Decorated. Window extends Window { public Decorated. Window (Window w) { undecorated = w; } void redraw() { undecorated. redraw(); } (4) Window w =. . . ; Window hsw = new Window. With. Hscroll(w); Window thsw = new Window. With. Title(hsw); Window bthsw = new Window. With. Border(thsw); private Window undecorated; }; 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 79
Structural Patterns Decorator 1 hsw. redraw() (4) Window redraw() w Some. Window 3 redraw() comp 1 Decorated. Window 3 redraw() 2 Window. With. Title Window. With. Border redraw() draw. Title() redraw() draw. Border() Window. With. HScroll 1 redraw() draw. HScroll() hsw 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 80
Structural Patterns Decorator thsw. redraw() 1 (4) Window redraw() comp 1 w Some. Window 5 redraw() Decorated. Window redraw() 3 2 Window. With. Title 1 redraw() draw. Title() thsw 19/03/2018© Jean-Paul Rigault, 20002003 5 4 Window. With. Border redraw() draw. Border() Window. With. HScroll redraw() 3 draw. HScroll() hsw Design Patterns: Introduction and Examples in Java 81
Structural Patterns Decorator n (5) Component Structure 1 op() . . . comp Concrete. Comp 1 Decorator op() comp. op() super. op() added. Op() 19/03/2018© Jean-Paul Rigault, 20002003 Decoration 1 op() added. Op() Design Patterns: Introduction and Examples in Java Decoration 2 op() . . . 82
Structural Patterns Decorator n (6) Decorator is a major pattern in Java n e. g. , Java IO system Buffered. Reader buf. Read = new Buffered. Reader( new Input. Stream. Reader( new File. Input. Stream(filename))); 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 83
Structural Patterns Decorator n (7) Consequences n Transparent enclosure n n Better flexibility than static inheritance Functionalities can be added incrementally Sometimes too general n o o Decorations can be composed in any order The decorated object is not the base object o o The decorated component has the same properties as the base component (plus some new ones. . . ) The system must not rely on object identity Difficult to “undecorate” in any order Lot of small objects o Easy to build, not so easy to understand 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 84
Structural Patterns Composite and Decorator * Obj Concrete. Obj Composite Var 1 Obj Concrete. Obj Decorator Deco 1 Deco 2 Var 2 Composite 19/03/2018© Jean-Paul Rigault, 20002003 1 Decorator Design Patterns: Introduction and Examples in Java 85
Structural Patterns Facade n Intent n n Provide a unified interface to a subsystem Consequence n n n Client Facade Subsystem easier to use Weaker dependency n including compile-time The subsystem parts remain accessible directly if needed 19/03/2018© Jean-Paul Rigault, 20002003 Subsystem Design Patterns: Introduction and Examples in Java 86
Structural Patterns Flyweight n Intent n n (1) Use sharing to support a large number of fine-grained objects Example: characters in a text processor Character code geometric info style size location draw(context). . . 19/03/2018© Jean-Paul Rigault, 20002003 Intrinsic state (sharable) Extrinsic state (context dependent Design Patterns: Introduction and Examples in Java 87
Structural Patterns Flyweight line (2) to be or not to be a b c d e f g h i j k l m flyweight pool n o p q r s t u v w x y z (geometric font. . . information) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 88
Structural Patterns Flyweight n (3) Structure Flyweight. Factory get. Flyweight(key) if flyweight[key] already exists return it; otherwise allocate it in pool and return it * Flyweight op(extrinsic_state ) Concrete. Flyweigh t intrinsic_state op(extrinsic_state) Client 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 89
Structural Patterns Flyweight n (4) Consequences n Memory saving increases with n n n o Smaller number of intrinsically different instances, bigger number of objects Bigger intrinsic state (shared) Computed (not stored) extrinsic state Cost for transferring, finding, computing, or storing extrinsic state 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 90
The Go. F Book Universal Design Patterns Behavioral Patterns
Behavioral Patterns n n n n Command Strategy State Observer Visitor Template Method Memento 19/03/2018© Jean-Paul Rigault, 20002003 n Miscelleaneous behavioral patterns n n Chain of Responsibility Interpretor Iterator Mediator Design Patterns: Introduction and Examples in Java 92
Behavioral Patterns Command n Intent n n (1) Encapsulate a request (function) into an object (reification) Example: a menu system Menu cmd. execute() File f open() print(). . . 19/03/2018© Jean-Paul Rigault, 20002003 * Menu. Item clicked() Print. Command execute() cmd Command execute() Open. Command execute() f. print() Design Patterns: Introduction and Examples in Java 93
Behavioral Patterns Command n (2) Structure Invoker Command execute() Receiver rcv Concrete. Command action() state action parameters execute() rcv. action() 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 94
Behavioral Patterns Command n (3) Consequence n Decoupling the call of the operation from its execution n Operations are first class objects n n n Easy to add new commands The same operation may be invoked by several ways (menu, button, click, command line…) They can have attributes, memorize information. . . Special effects like Undo/Redo… Operations may be combined into complex data structures, such as Composites (macros) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 95
Behavioral Patterns Strategy n Intent n n n (1) Encapsulate a family of interchangeable algorithms Let the algorithm vary independently from the client Structure Context Strategy algo() Strategy_1 algo() 19/03/2018© Jean-Paul Rigault, 20002003 Strategy_2 algo() Design Patterns: Introduction and Examples in Java Strategy_2 algo() 96
Behavioral Patterns Strategy Raw_Text (2) Formatting. Strategy format() Screen. Formatting format() Te. XFormatting format() Typesetting format() Formatting. Strategy strategy = new Screen_Formatting(); . . . strategy. format(); 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 97
Behavioral Patterns Strategy n (3) Consequences Family of related algorithms used in an unified way n Alternative to sub-classing n Implementation choices n Elimination of conditional statements o Clients must know the characteristics of strategies to choose among them o Communication overhead between context and algorithm o Increased number of objects o Is this a pattern or just an other name for (inheritance) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples methods, dynamic 98 polymorphism (virtual functions, in Java n
Behavioral Patterns Command Strategy n n Both patterns encapsulate (reify) a family of functions In the Command pattern n The concrete commands usually do different operations Commands are intended to be first class objects In the Strategy pattern n n The concrete strategies perform the same operation but with different algorithms First class citizenship is less a concern 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 99
Behavioral Patterns State n (1) Intent n Allow an object to change its behavior when its internal state change n n A sort of state-dependent strategy The object interface does not change, but the object appears as if its (sub-)type had changed 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 100
Behavioral Patterns State n Example state Politician. State Politician speak() change. State() (2) state. speak() # bla. Bla() # speak. Freely() Politician. In. Public Politician. In. Private speak() bla. Bla() 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java speak. Freely() 101
Behavioral Patterns State n (3) Consequences n n Localize and partition state specific behavior Make state transitions explicit n n State objets may be shared n o o Eliminate conditional statements If they have no instance variables, they can even be singleton Increase the number of classes Which class is responsible for changing the state? the object class? then it will depend on all states o the (concrete) state classes? then each one depends 19/03/2018© Jean-Paul Rigault, 2000 on its successor state classes. . . in Java 2003 Design Patterns: Introduction and Examples o 102
Behavioral Patterns Observer n (1) Intent n When an object change state, update automatically all objects depending on its state x a x 10 y 50 z 20 b 40 30 15 c 50 20 65 x x a b c update Some computation a=50% b=30% c=20% 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 103
Behavioral Patterns Observer n Structure obs Observe r update() Subject attach(observer ) detach(observe r) notify() Concrete. Subje ct subject. State * forall obs. update() subj Concrete. Observer update() get. State() 19/03/2018© Jean-Paul Rigault, 20002003 (2) subj. get. State() Design Patterns: Introduction and Examples in Java 104
Behavioral Patterns Observer n (3) Consequences n n n o Abstract and minimal coupling between subject and observers Observers can be changed dynamically Support for broadcast communication Spurious updates 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 105
Behavioral Patterns Visitor n Intent n n n o Perform an operation on each element of a complex structure Make it possible to change the operation without changing the classes of the elements it operates on A kind of (abstract) active iterator Possibly the most difficult Go. F book pattern… o o to understand to set up correctly 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 106
Behavioral Patterns Visitor: Example Program n instr * Instr Several operations on the same representation n * instr n n n Simple. Instr n Block n Assignment Selection 19/03/2018© Jean-Paul Rigault, 20002003 . . . Drawing Type checking Interpreting Generating code etc. All these operations involve traversing the whole data structure Design Patterns: Introduction and Examples in Java 107
Behavioral Patterns Visitor: the Problem n What to do depend on both n n n the type of node that is visited (program, block, simple instruction…) the type of operation to perform (draw, type check…) f(node, op)? n n n Double dynamic dispatching (double polymorphism, functions that are doubly virtual… aka multimethods) Supported, e. g. , in CLOS Not supported in C++, Java, Smalltalk… n Possible solution: break the symmetry… (Make something static) 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 108
Behavioral Patterns Visitor: Node Side (1) Program draw() get. Type() generate() * instr Instr Node operations usable by the various visito (operations defined in specific nodes) Not necessarily 1 -1 mapping with visitor types Not necessarily the same in all types of nodes Simple. Instr Assignment draw() get. Type() generate() 19/03/2018© Jean-Paul Rigault, 20002003 * instr Block draw() get. Type() generate() Design Patterns: Introduction and Examples in Java 109
Behavioral Patterns Visitor: Visitor Side Visitor Here the symmetry visit(Program p) Each concrete node visiting functio is broken: static list visit(Block b) does whatever is needed to perform of concrete node types visit(Assignment a) the visiting operation. … Draw an assignment Type check an assignment Draw. Visitor TCVisitor Generate. Visitor visit(Program p) visit(Block b) visit(Assignment a) … 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 110
Behavioral Patterns Visitor: Node Side (2) Program draw() get. Type() generate() accept(visitor) visitor. visit(this) * instr Instr Simple_Instr Assignment draw() get. Type() generate() accept(visitor) Rigault, 200019/03/2018© Jean-Paul 2003 * instr visitor. visit(this) Block draw() get. Type() generate() accept(visitor) One accept function per each type of node simply calling the corresponding visitor function. Design Patterns: Introduction and Examples in Java 111
Behavioral Patterns Visitor: Flow of Control : Client <
Behavioral Patterns Visitor n Consequences n n n o Adding new operations (i. e. , new type of visitor) is easy Each visitor subclass localizes related operations (and separate unrelated ones) Visitor can accumulate state when traversing the elements Adding new concrete elements (i. e. , new types of node) is difficult o Hence the node hierarchy has better be stable The element interface must contains all the functions 19/03/2018© Jean-Paul Rigault, 2000 needed by the various visitors in Java 2003 Design Patterns: Introduction and Examples 113 o
Behavioral Patterns Visitor and Iteration n (1) When visiting a complex data structure (e. g. , a Composite), where to locate the responsibility for traversing the structure? n In the visitors, i. e. , in the visit() methods? n o o n Allow visitor specific traversals Need to duplicate the traversal code in all concrete visitors Risk of breaking the encapsulation of the elements In the elements, i. e. , in the accept() methods? The data structure itself is responsible for its traversal o Risk of useless visits (with respect to the visitor 19/03/2018© Jean-Paulfunctionality) Rigault, 20002003 Design Patterns: Introduction and Examples in Java 114 n
Behavioral Patterns Visitor and Iteration (2) Program n draw() get. Type() generate() accept(visitor) * instr Instr Here, traversal is under the responsibility of the data structure Simple. Instr Assignment draw() get. Type() generate() accept(visitor) 19/03/2018© Jean-Paul Rigault, 20002003 * instr Block draw() get. Type() generate() accept(visitor) left. accept(visitor) right. accept(visitor) forall i in instr do i. accept(visitor) done Design Patterns: Introduction and Examples in Java 115
Behavioral Patterns Visitor and Iteration Visitor (2) Here, traversal is under visit(Program p) the responsability of the visit(Block b) visitors visit(Assignment a) a. right. accept(this); … n a. left. accept(this); if a. right. get. Type() is convertible into a. left. get. Type() return a. left. get. Type() Draw. Visitor TCVisitor visit(Program p) visit(Block b) visit(Assignment a) … 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java a. left. accept(this) draw(“=“) a. right. accept(this) 116
Behavioral Patterns Visitor and Iteration Visitor visit(Program p) visit(Block b) visit(Assignment a) … n (3) Using iterators Iterator child = b. iterator(); while (!has. Next())) { child. next(). accept(this); }. . . Draw_Visitor TC_Visitor visit(Program p) visit(Block b) visit(Assignment a) … 19/03/2018© Jean-Paul Rigault, 20002005 Design Patterns: Introduction and Examples in C++ 117
Behavioral Patterns Template Method n n (1) No connection with C++ template classes and functions! Intent n Define the skeleton of an operation (the structure of an algorithm), deferring some steps to subclasses Abstract. Class algo() op 1() op 2() op 3() 19/03/2018© Jean-Paul Rigault, 20002003 Concrete. Class op 1() op 2() op 3() Design Patterns: Introduction and Examples in Java op 1() … op 2() … op 3() … 118
Behavioral Patterns Template Method public class Connection { Connection exchange () open() send() close() TCPConnection open() send() close() (2) public void exchange() { if (open()) { while (data_left) { send(data); } close(); } }. . . Serial. Connection open() send() close() } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 119
Behavioral Patterns Template Method n (3) Consequences n n The Hollywood Principle: “Don’t call us, we’ll call you” Fundamental method of code reuse n n n Capture common behavior (subtype independent) Particularly useful in libraries Operations: n n Abstract operations: must be overridden in concrete derived classes Hooks: may be overridden in derived classes n Usually defined to do nothing in base class 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 120
Behavioral Patterns Memento n (1) Intent n n Record the state of an object so that the object can be restored to this state later Do so without violating the encapsulation Originator <
Behavioral Patterns Memento n n Avoid violating the encapsulation Originator A Memento has 2 -- state save. State() : Memento interfaces restore. State(Memento m) (2) <
Behavioral Patterns Memento : Client (3) : Originator save. State() <
Behavioral Patterns Memento class State {. . . } class Originator { public Memento save. State() { return new Memento(_state); } (4) public class Memento { // Narrow interface (public) // Nothing? // Possibly finalize()? // Wide interface // (package access) Memento(State state) { _state = state; } public void restore. State(Memento m) { _state = m. get. State(); } State get. State() { return _state } . . . private State _state; } 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 124
Behavioral Patterns Memento n (5) Consequences n n Preserve encapsulation Simplify the Originator n o Memento may be expensive o o No need for special memorization operation/data within the Originator itself Size of the state information: cost for storing and copying it Some programming languages do not facilitate the two interfaces definition 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 125
Behavioral Patterns Miscellaneous Behavioral Patterns(1) n Chain of Responsibility n n n Avoid coupling the emitter of a request to its receiver Give a chance to (the first of) several objects to handle the request next Handler handle. Request() Consequences n n o Flexibility The handler objects may vary dynamically The handling of a request is not guaranteed 19/03/2018© Jean-Paul Rigault, 20002003 Concrete. Handler 1 handle. Request() if can handle it, do it; otherwise delegate to next Design Patterns: Introduction and Examples in Java 126
Behavioral Patterns Miscellaneous Behavioral Patterns(2) n Interpretor n n n Given a language, define a grammar, and embed an interpreter within the system Example: exchange using XML Iterator n n n Allow sequential access to the elements of a composite object without exposing its internal structure Allow several simultaneous traversals A well-known pattern! 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 127
Behavioral Patterns Miscellaneous Behavioral Patterns(3) n Mediator n Encapsulate into an object the communication between a set of other objects Colleague_2 Colleague_1 a. Mediator Colleague_3 19/03/2018© Jean-Paul Rigault, 20002003 Colleague_4 Colleague_5 Design Patterns: Introduction and Examples in Java 128
The Go. F Book Universal Design Patterns Selected References
Selected References n (1) General references n Design Patterns: Elements of Reusable Object. Oriented Software Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides Addison Wesley, 1995 (Exists also under HTML form on a CD-ROM) (The so-called “Gang of Four Book”, the Go. F book) n Pattern Hatching John Vlissides Addison Wesley, 1998 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 130
Selected References n (2) Origin of design patterns n The Timeless Way of Building Christopher Alexander Oxford University Press, 1979 n A Pattern Language: Towns Buildings Construction Christopher Alexander, Sara Izikawa, Murray Silverstein Oxford University Press, 1977 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 131
Selected References n (3) UML and Patterns n The Unified Modeling Language User Guide Grady Booch, James Rumbaugh, Ivar Jacobson, Addison Wesley, 1999 n Applying UML and Patterns (3 rd Edition) Craig Larman Prentice Hall, 2005 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 132
Selected References n (4) Design Patterns and Java n Design Patterns Java Workbook Steven J. Metsker Addison Wesley, 2002 n Design Patterns Explained: a New Perspective on Object-Oriented Design Allan Shalloway, James R. Trott Addison Wesley, 2002 n Effective Java: Programming Language Guide Joshua Bloch Addison Wesley, 2001 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 133
Selected References n (5) Design Patterns and C++ n Advanced C++: Programming Styles and Idioms James O. Coplien Addison Wesley, 1992 n Modern C++ Design: Generic Programming and Design Patterns Applied Andrei Alexandrescu Addison Wesley, 2001 19/03/2018© Jean-Paul Rigault, 20002003 Design Patterns: Introduction and Examples in Java 134
The End!


