0% found this document useful (0 votes)
6 views55 pages

Design Patterns Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views55 pages

Design Patterns Overview

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd

1

Design patterns

Nguyen Thanh Binh


Vietnam-Korea University of Information and Communication
Technology, The University of Danang
2 Introduction

 In many fields, design of systems is based on


pre-built patterns
 Examples
 Electronic circuits are usually designed by
assembling other components (such as power
supplies, filters, buses, etc.)
 Designing buildings can be assembled from
existing components…
3 Introduction

 A software design pattern is an organization


of software components, specifically classes
or objects, that provides a common solution
(template) to a problem
 Benefits of design patterns
 The designer's experiences are reused
 Code reuse, high maintainability
 Common problems will be solved quickly
thanks to the available solutions
 Reducing cost
4 Introduction

 Design patterns are proposed by


 Gamma, Helm, Johnson, and Vlissides
 The book “Design Patterns: Elements of Reusable
Object-Oriented Software”, Addison-Wesley
 Published in 1994
 23 design patterns for object-oriented design
 23 design patterns proposed by 4 people,
called “Gang of Four” or GoF
 “Description of communicating objects and
classes that are customized to solve a
general design problem in a particular
context” - Gamma, Helm, Johnson, and
Vlissides
5 What is a design pattern?

 A design pattern consists of


 Pattern name
 Intent
 Objective
 Problem
 When to apply design pattern?
 Problem, context, conditions for application
 Solution
 Not a specific solution but a template that can be
customized
 Consequences
 Describing the advantages and disadvantages of using
design patterns
6 Classification

 Design patterns are divided into three categories


according to the purpose of use
 Creational patterns deal with object creation
problems
 Structural patterns relate to the organization of
classes/objects
 Behavioral patterns describe interactions
between objects/classes
 Design patterns are divided into two categories
according to the scope of application
 Classes: describe the relationship between classes
 Objects: describe interactions between objects
7 Classification

Purpose

Creational (5) Structural (7) Behavioral (11)

Scope Class Factory Method Adapter (class) Interpreter


(4) Template Method

Object Abstract Factory Adapter (object) Chain of Responsibility


(19) Builder Bridge Command
Prototype Composite Iterator
Singleton Decorator Mediator
Facade Memento
Flyweight Observer
Proxy State
Strategy
Visitor
8 Creational patterns

 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

Documen Application Document doc =


t * docs 1 createDocument createDocument();
open() () [Link](doc);
close() newDocument() [Link]();
save() openDocument(
)

TextDocument TableDocument ProcessingTable ProcessingText


createDocument() createDocument()

<<create>>

return new TextDocument();


return new TableDocument();
11 Factory Method
 Structure Intent: Provides an interface for creating objects
in a superclass, but let subclasses decide which
class to instantiate/create

Defining factoryMethod() that


returns an object of Product
Defining the interface of the
objects that factoryMethod() …
creates Creator product = factoryMethod();
* 1 factoryMethod() …
Product anOperation()

ConcreteProduct CreateCreator return new ConcreteProduct(


factoryMethod()

<<create>>

Implementing interface Implementing factoryMethod()


Product that returns an object of
ConcreteProduct
12 Builder

 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()

PSExporte PDFExporter ASCIIExporte


r export() r
export() getPDFText( export()
getPSText ) getASCIIText
() … ()
… …
PSText PDFText ASCIIText

while(t=getNextToken()){ while(t=getNextToken()){ while(t=getNextToken()){


switch ([Link]){ switch ([Link]){ switch ([Link]){
case CHAR: case CHAR: case CHAR:
ouputPSChar([Link]); ouputPDFChar([Link]); ouputASCIIChar([Link]);
break; break; break;
case PARA: case PARA: case PARA:
ouputPSPara(); ouputPDFPara(); ouputASCIIPara();
break; break; break;
} } }
} } }
14 Builder
 Solution 2
builder
Exporter 1 1
Converter
export() convertChar()
beginPara()

PSConverter PDFConverter ASCIIConvert


while(t=getNextToken()){ convertChar( convertChar() er
switch ([Link]){ ) beginPara() convertChar()
case CHAR:
[Link]([Link]);
beginPara() … beginPara()
break; … getPDFText() …
case PARA: getPSText() getASCIIText(
[Link](); )
break; PSText PDFText ASCIIText
}
}

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()

+ Constructing and assembling parts of Product


the product by implementing the Builder
interface
+ Providing an interface (getPSText,
getPDFText) for retrieving the product Representing the complex object
under construction
16 Singleton

 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

- instance: SingleObject instance

- 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)

DrawingEdit Shape Text


or draw() content()
dimension() length()
width()

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

Client Target Adaptee


request() specificResques
t()

adapte
Adapter e
[Link] request()
st()
26 Adapter Intent: Converting the interface of a class
into another expected interface

 Adapter (class)
 Multiple inheritance

Client Target Adaptee


request() specificResques
t()

Adapter
[Link] request()
()

Question: How to apply Adapter (class) to the problem?


27 Composite

 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 )

Rectangl Line Text Picture forall g in graphics


e draw() draw() draw() [Link]()
draw() add(Graphic g) add g to list of
remove(Graphic graphics
)
29 Composite
 Example: a typical composite object structure
of recursively composed Graphic objects

aPicture

aRectangle aPicture aLine aText

aRectangle aLine aText


30 Composite

 Structure Intent: Composing objects into tree


structures to represent part-whole
hierarchies

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

InterfaceCompone Border Scroll


nt drawBorder() scrollTo()
draw()

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()

TextZone GraphicalZon Decorator


draw() e draw() [Link]
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()

Circle Rectangle ShapeDecorator


+draw() +draw() #decoratedShape:
Shape
+ShapeDecorator()
+draw()

RedShapeDecorator
+RedShapeDecorator(
)
+draw()
- setRedBorder()
36 Decorator
 Create a Shape interface

 Create classes implementing the Shape interface


37 Decorator
 Create abstract decorator class implementing
the Shape interface
38 Decorator
 Create concrete decorator class extending
the ShapeDecorator class
39 Decorator
 Use the RedShapeDecorator to decorate Shape objects
40 Behavioral Patterns

 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

 The tool will be developed


43 Observer
 Solution
for all o in
observer
[Link]()

Subject Observer
observer observerState=
attach(o Observer) update()
dettach(o [Link]()
Observer)
notify()

ConcreteSubject Table Histogram Circle


getState() update() update() update()
setState() observerSta observerSta observerSta
subjectState te te te
subject

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

 Typical interactions in Observer

aConcreteSubject aConcreteObserver anotherConcreteObserver


setState()

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
()

DrawDocume TextDocume TextApplication DrawApplication


nt nt doCreateDoc() doCreateDoc()
doRead() doRead() canOpenDoc() canOpenDoc()
aboutToOpenDoc aboutToOpenDoc
() ()
48 Template Method
 Method openDocument is called Template
Method

abstract class Application{


abstract public Document doCreateDoc();
 openDocument defines the
abstract public Boolean canOpenDoc();
… steps to open a document:
public void openDocument (String name) { checking document,
if (!canOpenDoc(name))
{ // cannot handle this document creating document objects,
return; adding documents to a set
} of documents, and reading
Document doc = doCreateDoc();
if (doc) {
documents from files.
[Link](doc);
aboutToOpenDoc(doc);  These steps will be
[Link](); implemented in subclasses
[Link]();
} (TextApplication and
} DrawApplication).

}
49 Template Method

 Structure Intent: Defining the skeleton of an algorithm in


the superclass but letting subclasses override
specific steps of the algorithm without changing
its structure

AbstractClass
primitiveOperation1();
templateMethod() …
primitiveOperation primitiveOperation2();
1() …
primitiveOperation
2()

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]

You might also like