Beruflich Dokumente
Kultur Dokumente
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
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()
SimpleFig Group
move()
Rectangle Triangle
...
move() move()
b carry
Half-adder
SimpleGate Operator
simul()
AndGate Inverter
...
simul() simul()
op() * op
Simple_Obj Composite
op()
Obj_Var1 Obj_Var2
...
op() op()
exec() * exec
Simple_Instr Block
Assignment Selection
...
exec() exec()
op() * op
Simple_Obj Composite
op()
Obj_Var1 Obj_Var2
...
op() op()
move() * move
Simple_Fig Group
move()
Rectangle Triangle
...
move() move()
op() * op
Simple_Obj Composite
op()
Obj_Var1 Obj_Var2
...
op() op()
simul() * simul
Simple_Gate Operator
simul()
And_Gate Inverter
...
simul() simul()
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)
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
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()
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
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
Creation Patterns
Abstract Factory
Builder
Prototype
Duplicating objects in Java
Singleton
Factory Method (Virtual Constructor)
Extensible implementation of Factory Method
MacButton MotifButton
MotifWidgetFact MacWidgetFact
ScrollBar
createWindow() createWindow()
createButton() createButton()
createScrollBar() createScrollBar()
MacScrollBar MotifScrollBar
Window w = factory.createWindow(...);
Button b = factory.createButton(...);
ScrollBar sb = factory.createScrollBar(...);
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
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
: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)
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)
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
Creator
factoryMethod()
Product
ConcreteCreator
<<create>> ConcreteProduct
factoryMethod()
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
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)
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)
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)
impl
Window ImplWindow
redraw() redraw()
raise() raise()
... ...
IconWindow MacWindow
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
Proxy
Interface_1 Interface_2
Bridge
Both are possible…
Separate specification/body
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
Example (cont.)
Using multiple inheritance?
Window
WindowWithHVScroll WindowWithTitle_Border
WindowWithBorderAndTitle
Window
WindowWithTitle WindowWithBorder WindowWithHScroll
redraw() redraw() redraw()
drawTitle() drawBorder() drawHScroll()
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
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)
BufferedReader bufRead =
new BufferedReader(
new InputStreamReader(
new FileInputStream(filename)));
1
Obj * Obj
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
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
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)
Intent
Encapsulate a family of interchangeable algorithms
Let the algorithm vary independently from the client
Structure
Context Strategy
algo()
Raw_Text FormattingStrategy
format()
Consequences
Family of related algorithms used in an unified way
Alternative to sub-classing
Implementation choices
algorithm
Increased number of objects
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
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
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
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
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.
…
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)
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)
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
(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()
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
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