You are on page 1of 44

WATERLOO

CHERITON SCHOOL OF
COMPUTER SCIENCE
Gang of Four (GoF)
Gang of Four (GoF)
OO Design Patterns
CS 446/646 ECE452
May 11
th
, 2011
IMPORTANT NOTICE TO STUDENTS
These slides are NOT to be used as a replacement for student notes.
These slides are sometimes vague and incomle!e on u"ose to spark class discussions
CS446/646 ECE452 2
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Motivation
Object Oriented Analysis (OOA)

domain problem designed as (domain) objects

addresses the functional challenges

what a system does

proides !"idance #or implementation


Object Oriented $esi!n (OO$)

domain problem solved as (implementation) objects

addresses the implementation challen!es

how a system reali%es OOA


CS446/646 ECE452 &
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Motivation
'ow can we improe OO$

identi#y common characteristics

creation( str"ct"re( behaio"r ) interactions

desi!n patterns (desi!n re"se)

!eneric bl"eprints (micro architecture)

lan!"a!e and implementation independent

two main catalo!"es

GoF: *an! o# +o"r (*amma( 'elm( ,ohnson( -lissides( .//5)

0OSA1 0attern Oriented So#tware Architect"re (2"schmann( et


al34 5iley( .//6)
CS446/646 ECE452 4
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Motivation
5hat is a $esi!n 0attern

common sol"tion to a reocc"rrin! problem in desi!n


Anatomy

name

problem/motiation

sol"tion

conse6"ences ) tradeo##s

which ones are important #or "s7


CS446/646 ECE452 5
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Design Patterns Classification
GoF Design Patterns
Creational Structural Behavioral
class
scope
object
scope
CS446/646 ECE452 6
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Design Patterns Classification
GoF Design Patterns
Creational Structural Behavioral
Factor !ethod
"bstract Factor
Builder
Prototpe
Singleton
"daptor # class
Bridge
Composite
Decorator
Facade
"daptor#object
Fl$eight
Pro%
&nterpreter
Chain of responsibilit
Command
&terator
!ediator
Template !ethod
!emento
'bserver
State
Strateg
(isitor
class
scope
object
scope
CS446/646 ECE452 8
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Design Patterns Classification
90"rpose: based classi#ication

creational1

concerns with creation process o# objects ) classes

str"ct"ral

composition o# classes ) objects

behaioral

characteri%es interaction & responsibility o# objects )


classes
CS446/646 ECE452 ;
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Design Patterns Classification
9Scope: based classi#ication

decided i# the pattern applies to mainly classes or objects


<wo cate!ories

class scope

relationship between classes ) s"bclasses

statically de#ined at r"n=time

object scope

object relationships (what type?)

can be manip"lated at r"ntime (so what?)


CS446/646 ECE452 /
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Design Patterns Classification
Creational class

de#ers object creation to


s"b=classes (factory
method)
Str"ct"ral class

inheritance to compose
classes (adapter)
2ehaioral class

"ses inheritance to
describe #low o# control(
al!orithms (template)
Creational object

de#ers object creation to


other objects (abstract
factory)
Str"ct"ral object

deals with object


assembly (adapter)
2ehaioral object

!ro"p o# objects wor>in!


to!ether to carry o"t a
tas> (iterator)
CS446/646 ECE452 .?
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton
@ntent

ensure a class only has one instance, and provide a


global point of access to it.
Constr"ction
CS446/646 ECE452 ..
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
public class Singleton {
private static final Singleton INSTANCE = new Singleton();

// Private constructor prevents
// instantiation from other classes
private Singleton() {}

public static Singleton getInstance() {
return INS!N"#;
}
}
Singleton
@ntent

ensure a class only has one instance, and provide a


global point of access to it.
Constr"ction
CS446/646 ECE452 .2
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton
Adanta!es

controlled access to the class instance(s)

can dictate who( and when a client can access

re#inement o# #"nctionality

ia inheritance/s"bclass
CS446/646 ECE452 .&
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton
Adanta!es

ariable n"mber o# instances

the getInstance() method needs modi#ication

what else needs to change?


CS446/646 ECE452 .4
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton
A closer loo> at Sin!leton

re"se

separation o# concerns

!lobal presence

state#"l s3 stateless

m"ltiple instances

li#e cycle
CS446/646 ECE452 .5
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
Ae"se

co"plin!

res"lts in ti!hter co"plin!

co"ples with the eBact type o# the sin!leton object

pass by re#erence to red"ce co"plin!7


CS446/646 ECE452 .6
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
Ae"se

co"plin!

res"lts in ti!hter co"plin!

co"ples with the eBact type o# the sin!leton object

pass by re#erence to red"ce co"plin!7


public voi$ $oSomething(){
Worker worker = Worker.getInstance()
wor%er&perform();
}
public voi$ $oSomething(Worker worker){
wor%er&perform();
}
CS446/646 ECE452 .8
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
Ae"se

inheritance

easy to eBtend #"nctionality in s"bclasses

not easy to oerride the object instance in s"bclasses


CS446/646 ECE452 .;
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
Separation o# concerns

sin!leton class responsible #or creation

acts as a b"ilder/#actory

what i# we were to separate the two concerns

eBample

database connection as a sin!leton

system . "ses a sin!leton to ens"re only a sin!le database


connection

system 2 needs to connection pool o# .? databases connections


CS446/646 ECE452 ./
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
*lobal presence

proides a !lobal access point to a serice

arenCt !lobal ariables bad7

can be accessed #rom anywhere

iolation o# layered access

not part o# method si!nat"re

dependency is not obio"s

re6"ires code inspection

a lar!e system may re6"ire many sin!letons

"se a re!istry/repository
CS446/646 ECE452 2?
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
State#"l sin!leton

same as a !lobal ariable in principle

arenCt !lobal ariables bad7

access concerns

synchroni%ation

conc"rrency D m"ltiple threaded "sin! a sin!leton

m"table s3 imm"table state


Stateless sin!leton

better then state#"l

can we hae a stateless sin!leton7


CS446/646 ECE452 2.
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
E"ltiple instances

distrib"ted systems

is it possible to hae a tr"e sin!leton in a distrib"ted


system7

!lobal re!istries/repositories

lan!"a!e (,aa) speci#ic concerns

initiali%ation D has to be thread sa#e

seriali%ation

class loaders
CS446/646 ECE452 22
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton A Closer Look
Fi#e=cycle ) li#e span

creation

la%y initiali%ation

sin!letons are lon! lied

as lon! as an applicationCs li#e span

re!istries can o"tlie applications

"nit testin! re6"ires short lied state

lan!"a!e (,aa) speci#ic concern

reloadin! sin!leton class (serlets)

loss o# state
CS446/646 ECE452 2&
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Singleton
5hen can @ "se a sin!leton

considerationsG.H

will eery "ser "se this class eBactly the same way7

will eery applications eer need only one instance7

sho"ld the clients be "naware o# the application

eBamples

,aa Eath class (stateless D static class)

top leel *I@ (window/#rame)

lo!!in!
)*+ http,--$$$.ibm.com-developer$orks-librar-co#single.html
CS446/646 ECE452 24
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter
@ntent

convert the interface of a class into another interface...


Adapter lets classes wor together that couldn!t otherwise
because of incompatible interface

also >nown as 9wrapper:

boolean al"es can be represented by

J.(?K( Jtr"e( #alseK( Jyes( noK

does this 6"ali#y as an adapter7


CS446/646 ECE452 25
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Motivation
.eed to add /Te%t0 capabilit to our dra$ing editor.
Consider an off the shelf Te#!$ie% component
CS446/646 ECE452 26
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Motivation
Obserations

can be done in two ways

object composition (shown aboe)

inheritance

Shape proides 9interface: and <eBt-iew proides an


implementation

Fets try to draw this7


CS446/646 ECE452 28
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter Class
Ae6"irement

re6"ires m"ltiple inheritance


$hat about implementations that do not support multiple
inheritance 12ava34
CS446/646 ECE452 2;
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter Object
Ae6"irement

ia object composition
CS446/646 ECE452 2/
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter Class vs. Object
Class

commitment to a
concrete adaptee class

not to its s"bclasses


(class hierarchy)

allows #or speciali%ation

how7

static in nat"re
Object

can "se many adaptees

incl"din! s"b=classes

harder to oerride the


adaptee behaior

why7
CS446/646 ECE452 &?
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter Class vs. Object
CS446/646 ECE452 &.
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter & Dependency Inversion
Client
laer
Business
laer
5tilit
laer
Client
laer
Business
laer
5tilit
&nterface
Business
&nterface
5tilit
laer
Simple 6aers "bstract 6aers
$ependency @nersion ($@)

deco"ple hi!h leel layer #rom lower leel layer(s)


CS446/646 ECE452 &2
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Dependency Inversion Example
@mplications

2"tton implementation
relies on Famp

any chan!es to Famp will


impact 2"tton

what i# we want to reuse


2"tton class with a
di##erent component

s"ch as a motor
CS446/646 ECE452 &&
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Dependency Inversion Example
$ependency @nersion to Aesc"e

loo>s !ood (7)

still a dependency le#t


CS446/646 ECE452 &4
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Dependency Inversion Example
Obseration

adapter enhanced the desi!n

increased re="sability at the price o# compleBity


CS446/646 ECE452 &5
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter
'ow m"ch adaptation is reasonable7
CS446/646 ECE452 &6
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge
@ntent

decouples an abstraction from its implementation so the


two can vary independently

does this not so"nds li>e an adapter7

will ta>e a closer loo> later


CS446/646 ECE452 &8
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge
CS446/646 ECE452 &;
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge
Bridge
CS446/646 ECE452 &/
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge Example
Solution via inheritance
"o&lem', $hat if $e have to
support another platform4
"o&lem(, client code is tied to
an implementation.
For portable code7 the client
should not refer to an
implementation
Problem
CS446/646 ECE452 4?
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge Example
Solution, 5se bridge pattern to place abstraction and
implementation in t$o different hierarchies
CS446/646 ECE452 4.
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge Example
Solution, 5se bridge pattern to place abstraction and
implementation in t$o different hierarchies
Bridge
CS446/646 ECE452 42
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Bridge
+eat"res

#leBible bindin! between abstraction ) implementation

two class hierarchies

clients are deco"pled


CS446/646 ECE452 4&
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter & Bridge
Common Elements

#leBibility ia indirection

re6"est #orwardin!
CS446/646 ECE452 44
WATERLOO
CHERITON SCHOOL OF
COMPUTER SCIENCE
Adapter & Bridge
$i##erence in intent

adapter

resoles incompatibilities between two eBistin! inter#aces

two inter#aces are independent and can eole separately

co"plin! is "n#oreseen

adapts components a#ter they hae been desi!ned

brid!e

connects an abstraction and its many implementations

eol"tion is in accordance with the base abstraction

co"plin! between the abstraction and the implementations are


>nown

You might also like