Sie sind auf Seite 1von 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
(V1.2)

Jean-Paul Rigault
Professor
University of Nice Sophia Antipolis
Polytechnic Engineering School
Department of Computer Science
Email: jpr@essi.fr
Contents
 Motivation
 With a simple example
 Characterization of Design Patterns
 The universal Design Patterns (from the GoF
Book)
 Classification
 Examples of implementation in Java
 References

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 3
Some preliminary remarks
 The class is too small as a reusability unit
 Cooperation between several classes/instances
 Code is not the only item that can be reused
 Reusing analysis, design
 Reusing (micro-)architectures recurrently found in
design

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 4
Introduction to Design
Patterns

Motivation,
Characterization
Motivation for Design Patterns
A Simple Example (1)
Method
instr ::= Instr
propagation
simple_instr exec() * exec
| block
block ::= instr*
simple_instr ::=
assignment SimpleInstr Block
| selection
exec()
...
Assignment Selection
...
exec() exec()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 6
Motivation for Design Patterns
A Simple Example (2)
Figure
 Graphic editor
 Grouping/Degroupin
move() * move
g

SimpleFig Group

move()

Rectangle Triangle
...
move() move()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 7
Motivation for Design Patterns
A Simple Example (3)
Circuit
 VLSI CAD
simul() * simul
a sum

b carry
Half-adder
SimpleGate Operator

simul()

AndGate Inverter
...
simul() simul()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 8
Motivation for Design Patterns
A Simple Example (3)
Objet

op() * op

Simple_Obj Composite

op()

Obj_Var1 Obj_Var2
...
op() op()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 9
Motivation for Design Patterns
A Simple Example (3)
Instr

exec() * exec

Simple_Instr Block

Assignment Selection
...
exec() exec()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 10
Motivation for Design Patterns
A Simple Example (3)
Objet

op() * op

Simple_Obj Composite

op()

Obj_Var1 Obj_Var2
...
op() op()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 11
Motivation for Design Patterns
A Simple Example (3)
Figure

move() * move

Simple_Fig Group

move()

Rectangle Triangle
...
move() move()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 12
Motivation for Design Patterns
A Simple Example (3)
Objet

op() * op

Simple_Obj Composite

op()

Obj_Var1 Obj_Var2
...
op() op()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 13
Motivation for Design Patterns
A Simple Example (3)
Circuit

simul() * simul

Simple_Gate Operator

simul()

And_Gate Inverter
...
simul() simul()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 14
Motivation for Design Patterns
A Simple Example (4)
Objet
 The Composite
pattern op() * op
 Recursive
aggregation
 Uniform
processing of Simple_Obj Composite
simple objects
op()
and composite
ones
 Method Obj_Var1 Obj_Var2
...
propagation
op() op()

06/08/2018© Jean-Paul Rigault, 2000-


2005 Design Patterns: Introduction and Examples in C++ 15
Motivation for Design Patterns
A Simple Example (5)
g3: Group
 The Composite
pattern
 Tree like data t1: Triangle g1: Group
structure
r2 r2: Rectangle
r1: Rectangle
t1
r1 r3: Rectangle
c1 c1: Circle
g3 g1 g2: Group

g2 e1: Ellipse
r3 e1
t2
t2: Triangle
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 16
Motivation for Design Patterns
A Simple Example (6)

 Design Patterns: reusable micro-architectures


 Appear recurrently in design
 Involve several classes/objects
 The class is not the ultimate reuse unit
 Non reducible to library code
 Recoding is needed for each application context
 Identify, name, characterize, evaluate… design
patterns
 The GoF book
 23 universal (fundamental) design patterns
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 17
Design Patterns
From Idioms to Frameworks (1)

Application programs

Application dependency

Language dependency
Frameworks

Design Patterns

Toolkits (libraries)

Idioms

Languages
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 18
Design Patterns
From Idioms to Frameworks (2)

 Idioms
 Reusable tricks (or traits, or micro-architectures…)
 Specific to a given programming language
 Examples
 Code sharing by private inheritance (C++)
 Delegation through operator-> (C++)
 “Resource acquisition is initialization” (C++)
 Nested classes (Java)
 Anonymous classes (Java)
 Immutable classes (Java)…
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 19
Design Patterns
Frameworks and Librairies
Librar Framewor
y k
Application General Application Application
specific code purpose specific code skeleton
code

main
06/08/2018© Jean-Paul Rigault, 2000-
main
2003 Design Patterns: Introduction and Examples in Java 20
Design Patterns
Characterization

 Name  Consequences
 Intention  Advantages
 Motivation  Drawbacks
 Applicability  Example of
 Structure implementation
 Participants  Language-dependent
 Collaboration  Similar patterns

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 21
Design Patterns
Characterization: Composite Pattern
(1)

 Name Object
 Composite op() *
op
 Intention
 Recursive aggregation
SimpleObj Composite
 Uniform processing of
simple objects and op()
composite ones
 Structure
ObjVar1 ObjVar2 ...
 UML diagram op() op()

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 22
Design Patterns
Characterization: Composite Pattern
(2)

 Consequences
 Homogeneous manipulation of simple and composite
objects (expected)
 Simplification of clients
 Extensibility: easy to add new components
(simple or composite)
 Sometimes too general
 Difficult to restraint the composition for a group of objects

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 23
Design Patterns
Characterization: Composite Pattern
(3)
 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<Figure> figs; // or any other collection

public void move(int dx, int dy) {


for (Figure fig : figs) {
fig.move(dx, dy);
}
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 24
Design Patterns
Conventions for UML Diagrams
<<interface>>
UML and Java: an interface AnInterface
UML: an operation signature
aMethod()
Java: a method signature
UML: realization
Java: implements
UML and Java: a abstract class (no instances)
AnAbstractClass
or possibly an interface
UML: an operation signature aMethod()
Java: an abstract method signature
UML: generalization
Java: extends
UML and Java: a concrete class (with instances)
AConcreteClass
UML: an operation with a method
Java: a method (with implementation) aMethod()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 25
The GoF Book Universal
Design Patterns

Overview
Design Patterns
The GoF 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 GoF book)
Addison Wesley, 1995
 23 “universal” design patterns
 Creation patterns (5)
 Structural patterns (7)
 Behavioral patterns (11)
 Many application context specific patterns have
2003 been defined by other authors
06/08/2018© Jean-Paul Rigault, 2000-
Design Patterns: Introduction and Examples in Java 27
Design Patterns
The GoF Book Patterns (2)

 Creation patterns  Abstract Factory


 Abstract the creation  Builder
of objects
 Prototype
 Make code
independent from the  Singleton
exact type of created  Factory Method
objects (Virtual Constructor)
 Ensure type
homogeneity during
creation

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 28
Design Patterns
The GoF Book Patterns (3)

 Structural patterns  Adapter (Wrapper)


 Make code  Bridge
independent from (Handle/Body)
(internal) structural
variations of objects  Composite
 Avoid explosion of  Decorator
class number as  Facade
implied by (multiple)
inheritance  Flyweight
 Separate  Proxy (Surrogate)
implementation from
specification
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 29
Design Patterns
The GoF Book Patterns (4)

 Behavioral patterns  Chain of


Responsibility
 Reified algorithms
 Command
 Assignment and
separation of  Interpretor
responsibilities during  Iterator
some process  Mediator
 Communication  Memento
between complex  Observer
objects  State
 Strategy
 Template Method
06/08/2018© Jean-Paul Rigault, 2000-
2003  Visitor
Design Patterns: Introduction and Examples in Java 30
The GoF Book Universal
Design Patterns

Creation Patterns
Creation Patterns
 Abstract Factory
 Builder
 Prototype
 Duplicating objects in Java
 Singleton
 Factory Method (Virtual Constructor)
 Extensible implementation of Factory Method

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 32
Creation Patterns
Abstract Factory (1)
Window w = new MacWindow(...);
Button b = new MacButton(...);
ScrollBar sb = new MacScrollBar(...);

 Rigid (built-in) type dependency


 Changing interface style is difficult
 Adding a new interface style is difficult
 How to guarantee interface style consistency?

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 33
Creation Patterns
Abstract Factory (2)
Window
WidgetFactory

Catalog createWindow() MacWindow MotifWindow


of productscreateButton()
createScrollBar()
Button

MacButton MotifButton
MotifWidgetFact MacWidgetFact
ScrollBar
createWindow() createWindow()
createButton() createButton()
createScrollBar() createScrollBar()
MacScrollBar MotifScrollBar

06/08/2018© Jean-Paul Rigault, 2000- Mac family Motif family


2003 Design Patterns: Introduction and Examples in Java 34
Creation Patterns
Abstract Factory (3)

 Creation of the factory itself


WidgetFactory factory =
new MacWidgetFactory();
 Creation of objects
 Just order from the factory

Window w = factory.createWindow(...);
Button b = factory.createButton(...);
ScrollBar sb = factory.createScrollBar(...);

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 35
Creation Patterns
Abstract Factory (4)

 Applicability
 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

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 36
Creation Patterns
Abstract Factory (5)

 Consequences
 Abstraction of the object creation process
 It is easy to change or add a family of products
 Even dynamically!
 Consistency within a given family is enforced
 Introducing a new product is not easy
 Static list of all products in the abstract factory
 Related patterns
 Singleton, Factory Method, Builder

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 37
Creation Patterns
Builder (1)
Director Builder
construct() buildPartA()
buildPartB()
...
for all subparts
build the subpart
ConcreteBuilder Other
Separate the construction ConcreteBuilder
of a complex object from buildPartA()
its representation so that buildPartB()
the same construction ...
process can create getResult()
different representations. Product
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 38
Creation Patterns
Builder (2)

:Client
:Concrete
Builder
:Director
construct() buildPartA()

buildPartB()

buildPartC()
getResult()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 39
Creation Patterns
Builder (3)

joe: Client
Bouyges:
ConcreteBuilder
anArchitect: Director
buildHouse() doEarthwork()
layFoundations()
buildWalls()
doInternalWork()

getHouse()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 40
Creation Patterns
Builder (4)

 Consequences
 Separation between construction and internal
representation
 The internal representation and the construction process
may vary independently
 Fine control over the construction process
 Related patterns
 Abstract Factory (one shot construction)
 Composite (usually a Builder constructs a
Composite)

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 41
Creation Patterns
Prototype (1)

 Intention
 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)
 Thus a kind of polymorphic copy

SomeType anObject;
...
SomeType anotherObject =
anObject.duplicate();
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 42
Creation Patterns
Prototype (2)
 Implementation in Java: using clone()
 clone() is a (protected) method of class Object
 Its default implementation is hardly suitable
 Interface Cloneable does not declare clone()!
 The contract of clone() is not precise enough
 The meaning of “copy” depends on the class of the object
 Different objects: x.clone() != x ?
 Type: x.clone().getClass()== x.getClass()?
 Equality: x.clone().equals(x)?
 Interaction with constructors is dubious
 See Effective Java (Item 10) for details…
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 43
Creation Patterns
Prototype (3)

 Implementation in Java: using a Copy Constructor


 A C++-like approach! Safer than clone()
public abstract class SomeType { // or interface
public abstract SomeType duplicate();
// ...
}
public class SomeSubType extends SomeType {
public SomeSubType(SomeSubType a) { ... }
public SomeType duplicate() {
return new SomeSubType(this);
}
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 44
Creation Patterns
Prototype (4)

 Implementation in Java: deep copy using


serialization
public class SomeObject implements Cloneable {
public final SomeObject clone() {
ByteArrayOutputStream bOut = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(bOut);
out.writeObject(this);
out.close();

ObjectInputStream in =
new ObjectInputStream(
new ByteArrayInputStream(bOut.toByteArray()));
SomeObject obj = (SomeObject) in.readObject();

return obj;
06/08/2018© Jean-Paul Rigault, 2000-
}
2003 Design Patterns: Introduction and Examples in Java 45
Creation Patterns
Prototype (5)

 Consequences
 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
 Replace the class by one of its instance, a prototypal
instance
 Even useful in Java, in combination with reflection
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 46
Creation Patterns
Singleton

 A class with a unique instance


 A useful concept (but a useless pattern?)
 One printer spooler, one window manager in a
system, one factory…
 More delicate that it may seem..
 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++)
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 47
Creation Patterns
Singleton: a Simple Implementation
public class Singleton {  The protected
public static Singleton constructor allow
theInstance() { subclassing
return _instance;
 The protected
}
_instance can be
protected Singleton() { overriden by derived
... classes
}
 Note that singleton are
protected static seldom explicit; they
Singleton _instance = may simply appear as
new Singleton();
... class static variables
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 48
Creation Patterns
Factory Method (Virtual
Constructor)

 Problems with Abstract Factory: extensibility


 Difficult to add a new product
 The type of the object is imposed from outside

Figure File of figures


Figure pf; aCircle
aRectangle
Rectangle Ellipse
pf = the first figure aEllipse
in the file? aCircle
Square Circle aSquare

06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 49
Creation Patterns
Factory Method implementation (1)
 Using an ordinary constructor?
 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++)?
 Which size to allocate?
 new cannot be virtual since it is static

 Moreover, which constructor to call after new?


06/08/2018© Jean-Paul Rigault, 2000-
2003
 Impossible in Design Java…
Patterns: Introduction and Examples in Java 50
Creation Patterns
Factory Method implementation (2)

 Using a static scheme?


public class Figure {
public static Figure create(...) {
TypeTag 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(...);
...
} ...
}
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 51
Creation Patterns
Factory Method implementation (3)

 Towards an extensible scheme


 The base class should have no static knowledge
about its derived classes
 Instances should be constructed through their class
constructor
 Indeed the constructors may have side-effects of
interest...
 Thus, only a derived class knows how to construct its
instances
 So we need a method to delegate object creation to
subclasses
 It should be possible to add derived classes without
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 52
Creation Patterns
Factory Method pattern (1)

Creator

factoryMethod()
Product

ConcreteCreator
<<create>> ConcreteProduct
factoryMethod()

return new ConcreteProduct(..)

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 53
Creation Patterns
Factory Method pattern (2)

Figure  The Product and the


Creator hierarchies may be
create()
(and often are) identical
factoryMethod()
 The create()
static method
dispatches the
Rectangle Ellipse
creation to the
factoryMethod() factoryMethod() adequate
factoryMethod()
return new Rectangle(...) return new Ellipse(...)

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 54
Creation Patterns
Extensible Factory Method (1)

 An extensible scheme to construct an object


1. Get the type tag of the object (reading from a file,
deserializing, XML tag…)
2. Find out which class corresponds to the tag
3. Obtain (dynamically) an object of the corresponding
type
4. Invoke the Factory Method through this “exemplar” or
“prototype” object
 Steps 2 and 3 are the key
 either use a map<tag, prototype> (C++, Java)
 or use dynamic class loading or reflection (Java)
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 55
Creation Patterns
Extensible Factory Method (2)
 Example using Java Class.forName()
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.forName(name).newInstance();
// 4. Call Factory Method to create the instance
return fig.factoryMethod(...);
} ...
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 56
Creation Patterns
Extensible Factory Method (3)
 Example using Java Class.forName() (cont.)
public class Rectangle extends Figure {

public Rectangle factoryMethod(...) {


// Read Rectangle attributes (from the file…)
attributes = ...;
// Construct a new Rectangle
return new Rectangle(attributes);
}
...
}

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 57
Creation Patterns
Extensible Factory Method (4)
 Other implementations of Factory Method in
Java
 Defining an ad hoc ClassLoader
 Using serialization/deserialization
 readObject() is indeed a kind of virtual constructor
 However, a constructor is not invoked to initialize the
object!

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 58
The GoF Book Universal
Design Patterns

Structural Patterns
Structural Patterns
 Adapter (Wrapper)
 Bridge (Handle/Body)
 Proxy (Ambassador, Surrogate)
 Adapter, Bridge, and Proxy
 Composite
 Decorator
 Composite and Decorator
 Facade
 Flyweight
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 60
Structural Patterns
Adapter (Wrapper) (1)

 Intent
 Adapt a class interface so that the application may use
it
 Separate the application API from a toolkit/library API

Adaptation Toolkit class


Client Application
appli_interface tool_interface

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 61
Structural Patterns
Adapter (Wrapper) (2)

 Adaptation using inheritance (Class Adapter)


target
adaptee
Client Stack
MyVector
push()
get(int i)
pop()

adapter StackVector
push() delegate to
pop() get()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 62
Structural Patterns
Adapter (Wrapper) (3)

 Adaptation using composition (Object Adapter)


target adaptee
Client Stack MyVector
vec
push() get(int i)
pop()

adapter StackVector
push() delegate to
pop() vec.get()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 63
Structural Patterns
Adapter (Wrapper) (4)
 Class adapter
 Adaptation through “multiple” inheritance
 Only one adapter/adaptee object, no indirection
 Code sharing through “implementation” inheritance
 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
 If the adaptee is the head of a class hierarchy,
polymorphism can be used
06/08/2018© Jean-Paul Rigault, 2000-
2003  Access through Designindirection
Patterns: Introduction and Examples in Java 64
Structural Patterns
Adapter (Wrapper) (5)

 Special case of Adapter: merging hierarchies


Figure Image
fig img
draw() paint()

Rectangle Ellipse PictImage JpegImage

TiffImage
Square Circle ClippedImage

draw()
fig.draw() paint() img.paint()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 65
Structural Patterns
Bridge (Handle/Body) (1)

 Intent
 Decouple an abstraction (interface) from its
implementation so that both may vary independently

Interface implImplementation

op1() implOp1()
op2 () implOp2 ()
... Each operation is ...
delegated to one
(or a combination of)
operation(s) of the
implementation
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 66
Structural Patterns
Bridge (Handle/Body) (2)

 Using multiple Window


inheritance? redraw()
raise()
 Explosion of the lower()
iconify()
number of derived deiconify()
classes drawLine()
drawText()
...

DialogWindow ApplicWindow MacWindow

IconWindow XWindow Win32Window


06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 67
Structural Patterns
Bridge (Handle/Body) (3)

impl
Window ImplWindow
redraw() redraw()
raise() raise()
... ...

DialogWindow ApplicWindow XWindow Win32Window

IconWindow MacWindow

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 68
Structural Patterns
Bridge (Handle/Body) (4)

 How to select a particular windowing


system?
 Through an Abstract factory, of course!

public interface WindowSystemFactory {


public WindowImpl createWindowImpl();
public ColorImpl createColorImpl();
public FontImpl createFontImpl();
...
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 69
Structural Patterns
Bridge (Handle/Body) (5)

 Consequences
 Decouple interface from implementation
 Eliminate compile-time dependencies
 Allow run-time configuration or even change of
implementation
 Better structure
 Improve extensibility
 “The key to extensibility is indirection”
 Hide implementation details
 Avoid private members from being visible (opaque
types)
2003
Adapt the interface
 Jean-Paul Rigault, 2000-
06/08/2018©
Design Patterns: Introduction and Examples in Java 70
Structural Patterns
Proxy (Surrogate, Ambassador) (1)

 Intent
 Controlling the access to an object through a
surrogate object
SomeObject
op1()
op2()
...

real.op1()
real
RealObject ProxyObject
op1() op1()
op2() op2() real.op2()
... ...
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 71
Structural Patterns
Proxy (Surrogate, Ambassador) (2)

 Types of proxies
 Remote proxy (Ambassador)
 A local representative for an object in a different
address space (possibly on a remote machine)
 Virtual proxy
 Create expensive object on demand
 Similar to virtual memory handling
 Protection proxy (Body Guard)
 Handle access rights to an object

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 72
Structural Patterns
Proxy (Surrogate, Ambassador) (3)

 Types of proxies (cont.)


 Smart reference (Smart Pointer)
 Replacement for a pointer, with additional behavior
 Reference counting (sharing objects)
 Multi-threads synchronization
 Loading on demand (see Virtual Proxy)

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 73
Structural Patterns
Adapter, Bridge, Proxy (1)
 Related patterns with similar
structure SomeObject
 Indirect access through an Interface_1
intermediary object
 Intents are different
obj
 Interfaces are different
AnotherObject
 Adapter
Interface_2
 Interface_1  Interface_2

 Proxy
 Interface_1  Interface_2

 Bridge
 Both are possible…

 Separate specification/body

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 74
Structural Patterns
Composite

 See the Object


op() *
Introduction op
 The Composite
pattern SimpleObj Composite
 Recursive
op()
aggregation
 Uniform
processing of
simple objects ObjVar1 ObjVar2 ...
op() op()
and composite
ones
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 75
Structural Patterns
Decorator (1)

 Intent
 Attach responsibilities to an object dynamically
 Avoid explosion of class number due to (multiple)
inheritance
title
 Example title bar

border
still
a window vertical scroller

application window

horizontal scroller

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 76
Structural Patterns
Decorator (2)

 Example (cont.)
 Using multiple inheritance?
Window

WindowWithHScroll WindowWithVScroll WindowWithTitle WindowWithBorder

WindowWithHVScroll WindowWithTitle_Border

WindowWithBorderAndTitle

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 77
Structural Patterns
Decorator (3)
undecorated
Window
 Example (cont.) redraw() 1
 Using the
Decorator pattern
other sorts DecoratedWindow
of windows
undecorated.redraw()
redraw()

Window
WindowWithTitle WindowWithBorder WindowWithHScroll
redraw() redraw() redraw()
drawTitle() drawBorder() drawHScroll()

super.redraw(); super.redraw(); super.redraw();


drawTitle() drawBorder() drawHScroll()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 78
Structural Patterns
Decorator (4)
class DecoratedWindow Window w = ...;
extends Window {

Window hsw = new


public DecoratedWindow
WindowWithHscroll(w);
(Window w) {
undecorated = w;
Window thsw = new
}
WindowWithTitle(hsw);
void redraw() {
undecorated.redraw();
} Window bthsw = new
WindowWithBorder(thsw);
private
Window undecorated;
};
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 79
Structural Patterns
Decorator (4)
comp
hsw.redraw() 1 Window
redraw() 1
w
SomeWindow DecoratedWindow 3
3 redraw() redraw()

WindowWithTitle WindowWithBorder WindowWithHScroll


redraw() redraw() redraw()
drawBorder() 1 drawHScroll()
drawTitle()

hsw
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 80
Structural Patterns
Decorator (4)
comp
thsw.redraw() 1 Window
redraw() 1
w
SomeWindow DecoratedWindow 5
5 redraw() redraw()
3
2 4

WindowWithTitle WindowWithBorder WindowWithHScroll


redraw() redraw()
1 redraw() drawBorder() 3 drawHScroll()
drawTitle()

thsw hsw
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 81
Structural Patterns
Decorator (5)
comp
 Structure Component
op() 1

ConcreteComp1 Decorator
...
op() op()

comp.op()

Decoration1 Decoration2
super.op() ...
addedOp() op() op()
addedOp()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 82
Structural Patterns
Decorator (6)

 Decorator is a major pattern in Java


 e.g., Java IO system

BufferedReader bufRead =
new BufferedReader(
new InputStreamReader(
new FileInputStream(filename)));

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 83
Structural Patterns
Decorator (7)
 Consequences
 Transparent enclosure
 The decorated component has the same properties as
the base component (plus some new ones...)
 Better flexibility than static inheritance
 Functionalities can be added incrementally
 Sometimes too general
 Decorations can be composed in any order
 The decorated object is not the base object
 The system must not rely on object identity
 Difficult to “undecorate” in any order
 Lot of small objects
 Easy to build, not so easy to understand
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 84
Structural Patterns
Composite and Decorator

1
Obj * Obj

ConcreteObj Composite ConcreteObj Decorator

Var1 Var2 Deco1 Deco2

Composite Decorator
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 85
Structural Patterns
Facade
 Intent Client
 Provide a unified interface
to a subsystem

 Consequence Facade
 Subsystem easier to use Subsystem
 Weaker dependency
 including compile-time

 The subsystem parts


remain accessible directly
if needed

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 86
Structural Patterns
Flyweight (1)

 Intent
 Use sharing to support a large number of fine-grained
objects
 Example: characters in a text processor
Character
code Intrinsic state (sharable)
geometric info
style
size Extrinsic state (context dependent
location
draw(context)
...
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 87
Structural Patterns
Flyweight (2)

line 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)
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 88
Structural Patterns
Flyweight (3)

 Structure

FlyweightFactory * Flyweight
getFlyweight(key) op(extrinsic_stat
e)
if flyweight[key] already exists return it;
otherwise allocate it in pool ConcreteFlyweig
and return it ht
intrinsic_state
op(extrinsic_state)
Client
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 89
Structural Patterns
Flyweight (4)

 Consequences
 Memory saving increases with
 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

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 90
The GoF Book Universal
Design Patterns

Behavioral Patterns
Behavioral Patterns
 Command  Miscelleaneous
 Strategy behavioral patterns
 Command and  Chain of
Responsibility
Strategy
 Interpretor
 State  Iterator
 Observer  Mediator
 Visitor
 Template Method
 Memento
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 92
Behavioral Patterns
Command (1)
 Intent
 Encapsulate a request (function) into an object
(reification)
 Example: a menu system cmd
Menu MenuItem Command

cmd.execute()
* clicked() execute()

File f
PrintCommand OpenCommand
open()
print() execute() execute()
... f.print()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 93
Behavioral Patterns
Command (2)

 Structure
Invoker Command
execute()

Receiver rcv
ConcreteCommand
action()
state
execute()
action parameters
rcv.action()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 94
Behavioral Patterns
Command (3)

 Consequence
 Decoupling the call of the operation from its execution
 Easy to add new commands
 The same operation may be invoked by several ways
(menu, button, click, command line…)
 Operations are first class objects
 They can have attributes, memorize information...
 Special effects like Undo/Redo…
 Operations may be combined into complex data
structures, such as Composites (macros)

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 95
Behavioral Patterns
Strategy (1)

 Intent
 Encapsulate a family of interchangeable algorithms
 Let the algorithm vary independently from the client
 Structure
Context Strategy
algo()

Strategy_1 Strategy_2 Strategy_2


algo() algo() algo()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 96
Behavioral Patterns
Strategy (2)

Raw_Text FormattingStrategy
format()

ScreenFormatting TeXFormatting Typesetting


format() format() format()

FormattingStrategy strategy = new Screen_Formatting();


...
strategy.format();
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 97
Behavioral Patterns
Strategy (3)

 Consequences
 Family of related algorithms used in an unified way
 Alternative to sub-classing

 Implementation choices

 Elimination of conditional statements

 Clients must know the characteristics of strategies to

choose among them


 Communication overhead between context and

algorithm
 Increased number of objects

 Is this a pattern or just an other name for (inheritance)


06/08/2018© Jean-Paul Rigault, 2000-
2003 polymorphismDesign (virtual functions,
Patterns: Introduction and Examples inmethods,
Java dynamic 98
Behavioral Patterns
Command and Strategy

 Both patterns encapsulate (reify) a family of


functions
 In the Command pattern
 The concrete commands usually do different
operations
 Commands are intended to be first class objects
 In the Strategy pattern
 The concrete strategies perform the same operation
but with different algorithms
 First class citizenship is less a concern
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 99
Behavioral Patterns
State (1)

 Intent
 Allow an object to change its behavior when its
internal state change
 A sort of state-dependent strategy
 The object interface does not change, but the object
appears as if its (sub-)type had changed

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 100
Behavioral Patterns
State (2)

 Example
state PoliticianState
Politician
speak()
speak() # blaBla()
changeState() state.speak() # speakFreely()

PoliticianInPublic PoliticianInPrivate
speak() speak()

blaBla() speakFreely()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 101
Behavioral Patterns
State (3)

 Consequences
 Localize and partition state specific behavior
 Make state transitions explicit
 Eliminate conditional statements
 State objets may be shared
 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
 the (concrete) state classes? then each one depends
06/08/2018© Jean-Paul Rigault, 2000-
2003
on its successor state classes...
Design Patterns: Introduction and Examples in Java 102
Behavioral Patterns
Observer (1)
 Intent
 When an object change state, update automatically all
objects depending on its state
x x x
a b c
x 10 40 50
y 50 30 20
z 20 15 65
a b c
update

Some computation
a=50% b=30% c=20%
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 103
Behavioral Patterns
Observer (2)

 Structure
obs Observe
Subject r
attach(observer * update()
) forall obs
detach(observe obs.update()
r)
notify()
ConcreteSubje subj
ConcreteObserver
ct
subjectState update()
getState()
subj.getState()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 104
Behavioral Patterns
Observer (3)

 Consequences
 Abstract and minimal coupling between subject and
observers
 Observers can be changed dynamically
 Support for broadcast communication
 Spurious updates

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 105
Behavioral Patterns
Visitor

 Intent
 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 GoF book pattern…
 to understand
 to set up correctly

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 106
Behavioral Patterns
Visitor: Example
Program  Several operations
on the same
representation
instr
*  Drawing
Instr * Type checking
instr 

 Interpreting
 Generating code
 etc.
SimpleInstr Block
 All these operations
involve traversing
the whole data
Assignment Selection ... structure
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 107
Behavioral Patterns
Visitor: the Problem

 What to do depend on both


 the type of node that is visited (program, block, simple
instruction…)
 the type of operation to perform (draw, type check…)
 f(node, op)?
 Double dynamic dispatching (double polymorphism,
functions that are doubly virtual… aka multimethods)
 Supported, e.g., in CLOS
 Not supported in C++, Java, Smalltalk…
 Possible solution: break the symmetry… (Make
something static)
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 108
Behavioral Patterns
Visitor: Node Side (1)
Program
draw() Node operations usable by the various visito
getType() (operations defined in specific nodes)
generate() Not necessarily 1-1mapping with visitor types
Not necessarily the same in all types of nodes
*

instr
Instr *
instr

SimpleInstr
Block

Assignment draw()
getType()
draw() generate()
getType()
generate()
06/08/2018© Jean-Paul Rigault, 2000-
2003 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 typesvisit(Assignment a)
the visiting operation.

Draw an assignment Type check an assignment

DrawVisitor TCVisitor GenerateVisitor


visit(Program p) visit(Program p) visit(Program p)
visit(Block b) visit(Block b) visit(Block b)
visit(Assignment a) visit(Assignment a) visit(Assignment a)
… … …
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 110
Behavioral Patterns
Visitor: Node Side (2)
Program
draw()
getType()
generate()
accept(visitor)
visitor.visit(this)
*

instr
Instr *
instr
visitor.visit(this)

Simple_Instr
Block
One accept function per each
Assignment draw()
getType() type of node simply calling the
draw() generate() corresponding visitor function.
getType() accept(visitor)
generate()
accept(visitor)
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 111
Behavioral Patterns
Visitor: Flow of Control

:Client
<<create>> v :Visitor

a : ConcreteNodeA b : ConcreteNodeB

accept(v)
visit(a)
operationA()

accept(v)
visit(b)
operationB()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 112
Behavioral Patterns
Visitor

 Consequences
 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
 Hence the node hierarchy has better be stable
 The element interface must contains all the functions
needed
06/08/2018© Jean-Paul
2003
by theDesign
Rigault, 2000- various visitors
Patterns: Introduction and Examples in Java 113
Behavioral Patterns
Visitor and Iteration (1)

 When visiting a complex data structure (e.g., a


Composite), where to locate the responsibility for
traversing the structure?
 In the visitors, i.e., in the visit() methods?
 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
 Risk of useless visits (with respect to the visitor

06/08/2018© Jean-Paulfunctionality)
Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 114
Behavioral Patterns
Visitor and Iteration (2)
Program
draw()  Here, traversal is under
getType() the responsibility of the
generate()
accept(visitor) data structure
left.accept(visitor)
*
instr
right.accept(visitor)
Instr *
instr

SimpleInstr
Block forall i in instr
draw() do
Assignment
getType() i.accept(visitor)
draw() generate() done
getType() accept(visitor)
generate()
accept(visitor)
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 115
Behavioral Patterns
Visitor and Iteration (2)
Visitor
Here, traversal is under

visit(Program p) the responsability of the
visit(Block b)
visitors
visit(Assignment a) a.right.accept(this);
… a.left.accept(this);
if a.right.getType()
is convertible into
a.left.getType()
return a.left.getType()

DrawVisitor TCVisitor
visit(Program p) visit(Program p) a.left.accept(this)
visit(Block b) visit(Block b) draw(“=“)
visit(Assignment a) visit(Assignment a) a.right.accept(this)
… …
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 116
Behavioral Patterns
Visitor and Iteration (3)
Visitor
 Using iterators
visit(Program p)
visit(Block b)
visit(Assignment a) Iterator child = b.iterator();
… while (!hasNext())) {
child.next().accept(this);
}
...

Draw_Visitor TC_Visitor
visit(Program p) visit(Program p)
visit(Block b) visit(Block b)
visit(Assignment a) visit(Assignment a)
… …
06/08/2018© Jean-Paul Rigault, 2000-
2005 Design Patterns: Introduction and Examples in C++ 117
Behavioral Patterns
Template Method (1)

 No connection with C++ template classes and


functions!
 Intent
 Define the skeleton of an operation (the structure of an
algorithm), deferring some steps to subclasses
AbstractClass op1()

algo() op2()
op1()
op2() …
op3() ConcreteClass op3()

op1()
op2()
op3()
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 118
Behavioral Patterns
Template Method (2)
public class Connection {
Connection
exchange () public void exchange() {
open()
send() if (open()) {
close() while (data_left) {
send(data);
}
close();
TCPConnection SerialConnection
open() open() }
send() send() }
close() close()
...
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 119
Behavioral Patterns
Template Method (3)

 Consequences
 The Hollywood Principle: “Don’t call us, we’ll call you”
 Fundamental method of code reuse
 Capture common behavior (subtype independent)
 Particularly useful in libraries
 Operations:
 Abstract operations: must be overridden in concrete
derived classes
 Hooks: may be overridden in derived classes
 Usually defined to do nothing in base class

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 120
Behavioral Patterns
Memento (1)
 Intent
 Record the state <<create>>
of an object so Originator Memento
state state
that the object can
saveState() : Memento getState()
be restored to this restoreState(Memento m)
state later
 Do so without
violating the
state = m.getState()
encapsulation

return new Memento(state)

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 121
Behavioral Patterns
Memento (2)
 Avoid violating the
encapsulation <<create>>
Originator Memento
 A Memento has 2 -- state -- state
interfaces saveState() : Memento <<friend>> -- getState()
restoreState(Memento m)
 A wide interface,
accessible only
from the Originator  The Memento are passive

(access to objects
memento internal  The client application
data) never operates on or
 A narrow interface, consult the Memento data
used by client  Package access in Java
applications (only
may fake frienship
pass Memento’s
06/08/2018© Jean-Paul Rigault, 2000-
as
2003 parameters) Design Patterns: Introduction and Examples in Java 122
Behavioral Patterns
Memento (3)

: Client : Originator

saveState()
<<create>>
: Memento

restoreState()
getState()

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 123
Behavioral Patterns
Memento (4)
class State { ... } public class Memento {
// Narrow interface (public)
class Originator { // Nothing?
public Memento saveState() { // Possibly finalize()?
return new Memento(_state);
} // Wide interface
// (package access)
public void Memento(State state) {
restoreState(Memento m) { _state = state;
_state = m.getState(); }
}
State getState() {
... return _state
}
private State _state;
} private State _state;
}
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 124
Behavioral Patterns
Memento (5)

 Consequences
 Preserve encapsulation
 Simplify the Originator
 No need for special memorization operation/data within
the Originator itself
 Memento may be expensive
 Size of the state information: cost for storing and
copying it
 Some programming languages do not facilitate the two
interfaces definition

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 125
Behavioral Patterns
Miscellaneous Behavioral Patterns(1)
 Chain of Responsibility next
 Avoid coupling the emitter
of a request to its receiver Handler
 Give a chance to (the first handleRequest()
of) several objects to
handle the request
 Consequences
 Flexibility ConcreteHandler1
 The handler objects may
vary dynamically handleRequest()
 The handling of a request
is not guaranteed
if can handle it, do it; otherwise
06/08/2018© Jean-Paul Rigault, 2000-
delegate to next
2003 Design Patterns: Introduction and Examples in Java 126
Behavioral Patterns
Miscellaneous Behavioral Patterns(2)

 Interpretor
 Given a language, define a grammar, and embed an
interpreter within the system
 Example: exchange using XML
 Iterator
 Allow sequential access to the elements of a
composite object without exposing its internal
structure
 Allow several simultaneous traversals
 A well-known pattern!
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 127
Behavioral Patterns
Miscellaneous Behavioral Patterns(3)

 Mediator
 Encapsulate into an object the communication
between a set of other objects

Colleague_2 Colleague_1

aMediator
Colleague_4

Colleague_3
Colleague_5
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 128
The GoF Book Universal
Design Patterns

Selected References
Selected References (1)
 General references
 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 GoF book)
 Pattern Hatching
John Vlissides
Addison Wesley, 1998
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 130
Selected References (2)
 Origin of design patterns
 The Timeless Way of Building
Christopher Alexander
Oxford University Press, 1979
 A Pattern Language: Towns  Buildings  Construction
Christopher Alexander, Sara Izikawa, Murray Silverstein
Oxford University Press, 1977

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 131
Selected References (3)
 UML and Patterns
 The Unified Modeling Language User Guide
Grady Booch, James Rumbaugh, Ivar Jacobson,
Addison Wesley, 1999
 Applying UML and Patterns (3rd Edition)
Craig Larman
Prentice Hall, 2005

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 132
Selected References (4)
 Design Patterns and Java
 Design Patterns Java Workbook
Steven J. Metsker
Addison Wesley, 2002
 Design Patterns Explained: a New Perspective on
Object-Oriented Design
Allan Shalloway, James R. Trott
Addison Wesley, 2002
 Effective Java: Programming Language Guide
Joshua Bloch
Addison Wesley, 2001
06/08/2018© Jean-Paul Rigault, 2000-
2003 Design Patterns: Introduction and Examples in Java 133
Selected References (5)
 Design Patterns and C++
 Advanced C++: Programming Styles and Idioms
James O. Coplien
Addison Wesley, 1992
 Modern C++ Design: Generic Programming and
Design Patterns Applied
Andrei Alexandrescu
Addison Wesley, 2001

06/08/2018© Jean-Paul Rigault, 2000-


2003 Design Patterns: Introduction and Examples in Java 134
The End!

Das könnte Ihnen auch gefallen