Design Patterns Overview
Design Patterns Overview
Design patterns
Purpose
5 patterns
Factory Method
Abstract Factory
Builder
Prototype
Singleton
9 Factory Method
Motivation
We want to develop a set of office programs,
such as word processing (text), spreadsheets
(tables)... They share an interface. We have
defined:
An abstract class Application implements the
common features of the interface
An abstract class Document groups the
properties of documents that can be processed
by programs
Problem
Which class can create new objects of the
Document class in the code of the
Application class?
10 Factory Method
Solution
The subclasses of the Application class are
responsible for creating the Document objects
<<create>>
<<create>>
Motivation
We want to develop a text editor where
documents can be stored in various formats:
HTML, PostScript, PDF, ASCII…
Problem
How to organize the program so that a new
format can be added easily?
Limitations:
- Code redundancy
13 Builder - When adding a new document format,
the entire program code that outputs the
document must be rewritten
Solution 1 Exporter
export()
Benefits:
+ Saving code
+ Adding easily new format
types
15 Builder
Structure Intent: Separate the construction of a complex
object from its representation so that the same
construction process can create different
representations Specifying an abstract interface
Constructing an object using the
Builder interface (Converter) for creating parts of
a Product object
Director 1 builder 1
Builder
construct() buildPart()
ConcreteBuild
er
for (…)
[Link](); buildPart()
getResult()
Intent
Ensuring a class only has one object, and
provide a global point of access to it
Motivation
We want to develop an application and resource
management system on a computer. Some of the
objects on the system must be unique such as
printer queue, application manager, etc., and these
objects are used by a collection of applications.
Problem
How to organize program code so that an object is
unique?
17 Singleton
Bad solution
Using global variables to store objects
Limitation: different objects may be assigned to the
global variable
Good solution
There is only one class that can create an object
and access that unique object (singleton)
Singleton
static
uniqueSingleton
other attributs … return
static instance() uniqueSingleton;
other operations …
18 Singleton
Example with code
SingletonPatternDemo
+main()
uses
SingleObject
- SingleObject()
+getInstance() :
SingleObject
+showMessage()
19 Singleton
Create a Singleton Class
20 Singleton
Get the only object from the singleton class
21 Structural Patterns
7 patterns
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
22 Adapter
Motivation
We want to develop a graphic editing tool (draw
lines, polygons, text strings, ...). Interfaces for
graphic objects are defined by the abstract class
Shape. Each specific type of graphic object is
defined as a subclass of Shape, such as
LineShape, PolygonShape, TextShape, etc.
Problem
For the TextShape class, we want to use
operations on text that are already implemented
for the Text class in another application.
23 Adapter
Solutions
Defining the TextShape class so that it adapts
the interfaces of the Text class to the Shape
class. This can be done in two ways:
Solution 1: TextShape contains an object of Text
and inherits Shape – Adapter (object)
Solution 2: TextShape inherits Shape and the Text –
Adapter (class)
24 Adapter
Adapter (object)
LineShape TextShape
text
draw() draw()
dimension() dimension()
l = [Link]();
w = [Link]();
drawString([Link]
t())
25 Adapter Intent: Converting the interface of a class
into another expected interface
Adapter (object)
contains an object and inherits a class
adapte
Adapter e
[Link] request()
st()
26 Adapter Intent: Converting the interface of a class
into another expected interface
Adapter (class)
Multiple inheritance
Adapter
[Link] request()
()
Motivation
We want to develop a graphical editor that allows
complex pictures to be built from simple
components: simple components are grouped to
build larger components, and these components are
further grouped to create even larger components…
Problem
In the application, there are two types of objects:
the primitive graphic objects (lines, texts,
rectangles...) and the container objects that contain
them. How to handle these two types of objects in
the same way, that is, without having to distinguish
them?
28 Composite
Solution
Defining classes for the primitive objects (Line,
Text, Rectangle) and the container object so that
Defining common they implement the same interface (Graphic)
operations for both
primitive objects Container object can draw
(Line, Text, ...) and Graphic and also manipulate (add,
container objects remove) its child objects
(Picture). draw() graphics
add(Graphic)
Primitive objects remove(Graphic
can only draw )
aPicture
Client Component
operation() children
add(Component)
remove(Componen forall c in
t) children
[Link]()
Leaf Composite
operation( operation()
) add(Component)
remove(Componen
t)
31 Decorator
Motivation
We want to build a graphical user interface tool
that allows the design of window graphical
interface elements. Each of these interface
elements can have common properties such as
scroll bar, border, etc.
Problem
How to effectively implement these common
properties?
32 Decorator
Limitation: Combining a large number
of properties complicates the class
Solution 1 hierarchy
TextZone GraphicalZon
bordOption
draw() e
draw()
bordOption
scrollOption
BordTextZon BordScrollGraphicalZo
e ne
draw() draw()
33 Decorator
Advantages:
+ Common properties can be added more
easily
+ The class hierarchy is always simple
Solution 2
InterfaceCompone
nt component
draw()
BordDecorat ScrollDecorat
[Link](); or or
drawBord(); draw() draw()
drawBord() scrollTo()
bordWidth scrollPostion
34 Decorator
Structure Intent: Attaching additional responsibilities
to an object dynamically
Component
component
operation()
[Link]
();
ConcreteCompone Decorator
nt operation()
operation()
ConcreteDecorato
[Link]() r
;
operation()
addedBehavior();
addedBehavior()
addedState
35 Decorator
Example with code
Shape
+draw()
RedShapeDecorator
+RedShapeDecorator(
)
+draw()
- setRedBorder()
36 Decorator
Create a Shape interface
11 patterns
Chain of Responsibility
Command
Interpreter
Iterator
Mediator
Memento
Observer
State
Strategy
Template Method
Visitor
41 Observer
Motivation
We want to develop a tool to visually represent
data using different types of graphs. The same
data can be represented by different types of
graphs in different windows.
Problem
When there is a data change in each window,
the remaining windows must be changed
accordingly
42 Observer
Subject Observer
observer observerState=
attach(o Observer) update()
dettach(o [Link]()
Observer)
notify()
notify();
return
subjectState;
44 Observer
Intent: Defining a one-to-many dependency between
Structure objects so that when one object changes state, all its
dependents are notified and updated automatically
Providing an interface for Defining an updating interface
attaching and detaching for objects that should be
Observer objects notified of changes in a subject
Subject Observer
observer
attach(o Observer) update()
dettach(o
for all o in
Observer) observer
notify() [Link]()
ConcreteSubject ConcreteObserv
subject observerState=
getState() er
setState() update()
[Link]
subjectState return observerState ()
subjectState;
+ Maintaining a reference to a ConcreteSubject
object
+ Storing state of interest to ConcreteObserver
+ Implementing the Observer updating
objects
interface to keep its state consistent with the
+ Sending a notification to its observers when
subject's
its state changes
45 Observer
notify()
update()
getState()
update()
getState()
46 Template Method
Motivation
We want to develop software, including the
Application and Document classes, Application is
responsible for opening an existing document
from file. Document represents the information
of a document. Specific applications, such as
DrawApplication and TextApplication, inherit
from Application to meet some specific needs.
Problem
How to organize the program code of some
operations, such as opening documents
(openDocument) can be shared uniformly for
different specific applications?
Template Method
47 Template Method openDocument() uses
doCreateDoc(), canOpenDoc(),
aboutToOpenDoc()
Solution
Document Application
open() docs addDocument()
close() openDocument
save() ()
doRead() doCreateDoc()
canOpenDoc()
return new TextDocument()
aboutToOpenDoc
()
ConcreteClass
primitiveOperation
1()
primitiveOperation
2()
50 Template Method
Example with code
Game
+initialize()
+beginPlay()
+endPlay()
+play()
Cricket Football
+initialize() +initialize()
+beginPlay() +beginPlay()
+endPlay() +endPlay()
+play() +play()
51 Template Method
Create an abstract class with a template
method being final
52 Template Method
Create Cricket extending Game
53 Template Method
Create Football extending Game
54 Template Method
Use the Game's template method play() to
demonstrate a defined way of playing game
55 More on design patterns
References
Design Patterns: Elements of Reusable
Object-Oriented Software, Erich Gamma,
Richard Helm, Ralph Johnson, John Vlissides,
Addison-Wesley, 1994
[Link]
[Link]
[Link]