References:: - Applying UML and Patterns Craig Larman - Patterns in Java, Volume 2 Mark Grand
References:: - Applying UML and Patterns Craig Larman - Patterns in Java, Volume 2 Mark Grand
1
What are patterns?
2
The idea behind design patterns is simple:
Write down and catalog common interactions
between objects that programmers have
frequently found useful.
Result:
Facilitate reuse of object-oriented code
between projects and between programmers.
3
Some definitions of design patterns
• “Design patterns constitute a set of rules describing how to accomplish
certain tasks in the realm of software development.” (Pree, 1994)
• “Design patterns focus more on reuse of recurring architectural design
themes, while frameworks focus on detailed design… and
implementation.” (Coplien & Schmidt, 1995).
• “A pattern addresses a recurring design problem that arises in specific
design situations and presents a solution to it” (Buschmann, et. al.
1996)
• “Patterns identify and specify abstractions that are above the level of
single classes and instances, or of components.” (Gamma, et al., 1993)
4
Characteristics of Good patterns
• It solves a problem
• It is a proven concept
• The solution isn't obvious
• It describes a relationship
• The pattern has a significant human component
5
Types of patterns
Architectural Patterns
Expresses a fundamental structural organization or
schema for software systems.
Design Patterns
Provides a scheme for refining the subsystems or
components of a software system, or the relationships
between them.
Idioms
An idiom describes how to implement particular
aspects of components or the relationships between
them using the features of the given language.
6
Describing patterns
Name : It must have a meaningful name.
Problem: A statement of the problem.
Context: This tells us the pattern's applicability.
Forces: A description of the relevant forces and constraints and how they
interact/conflict with one another..
Solution: Static relationships and dynamic rules describing how to realize
the desired outcome.
Consequences: Implications( good and bad) of using the solution.
Examples: One or more sample applications of the pattern .
7
GRASP Patterns
Which class, in the general case is responsible?
• You want to assign a responsibility to a class
• You want to avoid or minimize additional dependencies
• You want to maximise cohesion and minimise coupling
• You want to increase reuse and decrease maintenance
• You want to maximise understandability
• …..etc.
8
GRASP patterns
General Responsibility Assignment Software Patterns
• Expert
• Creator
• Low Coupling
• High Cohesion
• Controller
• Polymorphism
• Pure Fabrication
• Indirection
• Law of Demeter
9
Expert
Problem:
What is the most basic principle by
which responsibilities are assigned in
object-oriented design?
Solution:
Assign a responsibility to the class that
has the information necessary to fulfil
the responsibility.
10
Expert : Example
Who is responsible for knowing the grand total of a sale in a typical Point of Sale
application?
Sale
date
time
Contain
s
1.. *
Product
Sales Specification
LineItem * Described-
by description
quantity price
UPC
11
Expert : Example
Need all SalesLineItem instances and their subtotals. Only Sale knows
this, so Sale is the information expert.
Hence
date
time
12
Expert : Example
But subtotals are needed for each line item(multiply quantity by price).
By Expert, SalesLineItem is expert, knows quantity and has association
with ProductSpecification which knows price.
t := total() 1*: [for each] sli := next() Sale
:Sale
date
time
2: st := subtotal()
total()
SalesLineItem
sli:SalesLineItem :SalesLineItem
SalesLineItem
quantity
2.1: p := price()
subtotal()
:Product Product
Specification Specification
description
price
UPC
New method price()
13
Expert : Example
Class Responsibility
14
Expert
• Maintain encapsulation of information
• Promotes low coupling
• Promotes highly cohesive classes
• Can cause a class to become excessively
complex
15
Creator
Problem:
Assign responsibility for creating a new
instance of some class?
Solution:
Determine which class should create
instances of a class based on the
relationship between potential creator
classes and the class to be instantiated.
16
Creator
B aggregates A objects
B contains A objects
B records instances of A objects
B closely uses A objects
B has the initializing data for creating A objects
17
Creator : Example
Sale
date
time
Contain
s
1.. *
Product
Sales Specification
LineItem * Described-
by description
quantity price
UPC
18
Creator : Example
Collaboration diagram is
date
time
1: create(quantity) New method
makeLineItem()
total()
:SalesLineItem
19
Creator
• Promotes low coupling by making instances
of a class responsible for creating objects
they need to reference
• By creating the objects themselves, they
avoid being dependent on another class to
create the object for them
20
Low Coupling
Problem:
To support low dependency and increased
reuse?
Solution:
Assign responsibilities so that coupling
remains low.
21
In object oriented languages, common form of coupling from
TypeX to TypeY include:
• TypeX has an attribute (data member or instance variable)
that refers to a TypeY instance, or TypeY itself.
• TypeX has a method which references an instance of
TypeY, or TypeY itself, by any means. These typically
include a parameter or local variable of type TypeY, or
the object returned from a message being an instance of
TypeY.
• TypeX is a direct or indirect subclass of TypeY.
• TypeY is an interface, and TypeX implements that
interface.
22
Low coupling
• Classes are easier to maintain
• Easier to reuse
• Changes are localised
23
Low Coupling
24
Low Coupling
Two possibilities:
2: addPayment(p)
:Sale
1.1. create()
:Payment
26
Some examples:
27
High cohesion
• Classes are easier to maintain
• Easier to understand
• Often support low coupling
• Supports reuse because of fine grained
responsibility
28
High Cohesion
1.Post
2: addPayment(p)
:Sale
29
High Cohesion
Giving responsibility to Sale supports higher cohesion in Post, as well as
low coupling.
1.1. create()
:Payment
30
Controller
Problem:
To assign responsibility for handling a
system event?
Solution:
If a program receive events from external
sources other than its graphical interface,
add an event class to decouple the event
source(s) from the objects that actually
handle the events.
31
The Controller pattern provides guidance for generally
acceptable choices.
Assign the responsibility for handling a system event
message to a class representing one of these choices:
1. The business or overall organization (a façade controller).
2. The overall "system" (a façade controller).
3. An animate thing in the domain that would perform the
work (a role controller).
4. An artificial class (Pure Fabrication representing the use (a
use case controller).
32
Benefits:
Increased potential for reuse. Using a controller object
keeps external event sources and internal event handlers
independent of each other’s type and behaviour.
Reason about the states of the use case. Ensure that the
system operations occurs in legal sequence, or to be able
to reason about the current state of activity and
operations within the use case.
33
Controller : Example
System events in Buy Items use case
enterItem()
endSale()
makePayment()
who has the responsibility for enterItem()?
34
Controller : Example
UPC Quantity
Total
Tendered Balance
presses button
Enter Item End Sale Make Payment
Cashier
onEnterItem()
1: enterItem(upc, qty)
controller
36
Bad design
– presentation layer coupled to problem domain
Object Store
UPC Quantity
Total
Tendered Balance
presses button
Enter Item End Sale Make Payment
Cashier
onEnterItem()
1: makeLineItem(upc, qty)
Domain Layer :Sale
37
Controller
• Using a controller object keeps external
event sources and internal event handlers
independent of each other’ type and
behaviour
• The controller objects can become highly
coupled and uncohesive with more
responsiblities
38
Polymorphism
Problem:
To handle alternatives based on types?
Solution:
When alternate behaviours are selected
based on the type of an object, use
polymorphic method call to select the
behaviour, rather than using if statement to
test the type.
39
Polymorphism : Example
Payment
amount
By Polymorphism, each
payment should
authorize itself
40
Example : Polymorphism
41
Polymorphism
• Easier and more reliable then using explicit
selection logic
• Easier to add additional behaviours later on
• Increased the number classes in a design
• May make the code less easier to follow
42
Pure Fabrication
Problem:
To not violate High Cohesion and Low Coupling?
Solution:
Assign a highly cohesive set of responsibilities to
an artificial class that does not represent anything
in the problem domain, in order to support high
cohesion, low coupling, and reuse.
43
Benefits:
High cohesion is supported because
responsibilities are factored into a class that
only focuses on a very specific set of
related tasks.
Reuse potential may be increased because of
the presence of fine grained Pure
Fabrication classes.
44
Example
Suppose, in the point of sale example, that support is needed to
save Sale instances in a relational database. By Expert, there is
some justification to assign this responsibility to Sale class.
However.
• The task requires a relatively large number of supporting
database-oriented operations and the Sale class becomes
incohesive.
• The sale class has to be coupled to the relational database
increasing its coupling.
• Saving objects in a relational database is a very general task for
which many classes need support. Placing these responsibilities
in the Sale class suggests there is going to be poor reuse or lots
of duplication in other classes that do the same thing.
45
Pure Fabrication : Example
save()
•The Sale remains well design, with high cohesion and low coupling
•The PersistentStorageBroker class is itself relatively cohesive
•The PersistentStorageBroker class is a very generic and reusable
object
46
Pure Fabrication
• Preserves low coupling and high cohesion
of classes
• Improve reusability of classes
47
Indirection
Problem:
To avoid direct coupling?
To de-couple objects so that Low coupling is
supported and reuse potential remains high?
Solution:
Assign the responsibility to an intermediate
object to mediate between other components or
services, so that they are not directly coupled.
48
Example : PersistentStorageBroker
49
Indirection : Example
By Indirection Modem
dial( )
receive( )
send( )
Modem::dial(phoneNum)
{
::OS_OpenPort(1);
::OS_Dial(phoneNUM)
}
50
Indirection
• Low coupling
• Promotes reusability
51
Law of Demeter
Problem:
To avoid knowing about the structure of
indirect objects?
Solution:
If two classes have no other reason to be
directly aware of each other or otherwise
coupled, then the two classes should not
directly interact.
52
Law of Demeter
It states that within a method, messages should only be sent
to the following objects:
53
Law of Demeter : Example
Sale
date : Date
isComplete : Boolean
POST time : Time Payment
Captures Paid-by
amountTendered
paymentAmount () : Float 1 1 becomeComplete () 1 1
endSale () makeLineitem () amountTendered () : Float
enteritem () makepayment ()
makePayment () payment () : Payment
total () : Float
54
Violates Law of Demeter : Example
POST::PaymentAmount()
{
prnt:= m_sale->Payment()
//Violates Law of DM
return prnt->amountTendered();
}
1.1:amt:=amountTendered():Float
prnt:Payment
Violates Law of DM
prnt is a 'Stranger' to
POST
55
Support Law of demeter
Sale
date : Date
isComplete : Boolean
POST:: PaymentAmount() time : Time
{
return m_sale -> Payment(); becomeComplete( )
makeLineitem( )
makePayment( )
payment( )
paymentAmount( )
total( )
1.1:amt:=amountTendered():Float
prnt:Payment
56
Law of Demeter
• Keeps coupling between classes low and
makes a design more robust
• Adds a small amount of overhead in the
form of indirect method calls
57
Law of Demeter – Time totalling example
58
Time totalling example
Employee - Instances of the Employee class represent an employee.
PayrollRules – The rules for paying an employee vary with the laws that
apply to the location where the employee works. Instances of the
PayrollRules class encapsulate the pay rules that apply to an employee.
PayPeriod – Instances of the Payperiod class represent a range of days for
which an employeee is paid in the same pay slip.
Shift – Instances of the Shift class represent ranges of time that the
employee worked.
TimeTotaller – The Timetotaller class is an abstract class that the PayPeriod
class uses to break the total hours worked during a pay period into
normal and overtime minutes.
C1TimeTot,C2TimeTot,C3TimeTot – Concrete subclasses for different
location of TimeTotaller that encapsulate the rules for breaking total
minutes worked into normal and overtime minutes worked.
59
The following interaction must occur:
• The pay period must become associated with an instance
of the subclasss of TimeTotaller appropriate for the
employee when the PayPeriod object is created.
• The TimeTotaller object must be able to examine each
shift in the pay period to learn the number of minutes
worked in each shift.
60
Bad time-totalling collaboration
PayPeriod class has no reason to know anything about the PayrollRules class
For TimeTotaller to have direct access to the collection of shifts that it needs
implies violation of the Shift class’s encapsulation of how it aggregates
Collection of shifts -- resulting in higher level of coupling
61
Good time-totalling collaboration
To preserve the level of cohesion and
coupling a less direct interaction may be
used.
This is done as shown by the following
collaboration diagram and the creation of
additional methods.
62
Good time-totalling collaboration
63
Law of Demeter – Time totalling example with added operations
64
S a m p le U P A r t if a c t R e la t io n s h ip s f o r U s e - C a s e R e a liz a tio n
D o m a in M o d e l
S a le 1 1 ..* S a le s
. . .
L in e I te m
d a te
. . .
. . . q u a n tity
t h e d o m a in o b je c ts , a ttr ib u t e s , a n d
d o m a in o b je c ts a s s o c ia tio n s th a t u n d e r g o s ta te c h a n g e s
U s e -C a s e M o d e l
: S y s te m
P r o c e s s S a le O p e r a t io n : m a k e N e w S a le
: C a s h ie r m ake
1 . C u s to m e r N e w S a le ( ) P o s t- c o n d it io n s :
a r r iv e s ... - . . .
2 . C a s h ie r s y s te m s y s te m
m akes new e n te rIte m
e v e n ts o p e ra tio n s
s a le . ( id , q u a n t ity )
c o n c e p tu a l 3 . C a s h ie r O p e r a t io n : e n t e r I te m
c la s s e s in e n t e r s it e m
th e id e n tifie r. e n d S a le ( )
P o s t- c o n d it io n s :
d o m a in 4 .... - A S a le s L in e It e m in s ta n c e
in s p ir e t h e s li w a s c r e a te d
nam es of m akeP aym ent - . . .
som e (a m o u n t)
s o ftw a r e
c la s s e s in Use Cases S y s te m S e q u e n c e D ia g r a m s C o n tr a c ts
t h e d e s ig n in a d d itio n to t h e u s e
c a s e s , r e q u ir e m e n ts th a t
s o m e id e a s a n d in s p ir a tio n fo r th e p o s t- m u s t b e s a t is f ie d b y t h e
c o n d itio n s d e r iv e f r o m th e u s e c a s e s d e s ig n o f th e s o ftw a r e
u s e -c a s e D e s ig n M o d e l
r e a liz a tio n
: R e g is te r : P r o d u c t C a ta lo g
m a k e N e w S a le ( )
c re a te ()
e n te r Ite m : S a le
( ite m ID , q u a n tity )
s p e c := g e tS p e c ific a t io n ( ite m ID )
a d d L in e Ite m ( s p e c , q u a n tity )
. . .
e n d S a le ( )
. . . . . . 65
b y C re a to r
and
C o n tr o lle r R e g is te r c r e a te s a
S a le b y C r e a to r b y C r e a t o r, S a le
:R e g is te r c re a te s a n e m p ty
m u ltio b je c t ( s u c h a s
a L is t ) w h ic h w ill
e v e n t u a lly h o ld
S a le s L in e Ite m
in s t a n c e s
m a k e N e w S a le ( )
c re a te () :S a le
c re a te () :S a le s
L in e Ite m
C A U T IO N :
th is a c tiv a tio n is im p lie d to b e w ith in th e T h is is n o t a S a le s L in e I t e m in s t a n c e . T h is is
c o n s tr u c to r o f th e S a le in s ta n c e a c o lle c t io n o b je c t ( s u c h a s a L is t ) t h a t c a n
h o ld S a le s L in e it e m o b je c t s .
66
b y C o n tr o lle r
:R e g is te r
m a k e N e w S a le ( )
67
b y C o n tr o lle r b y C r e a to r a n d L o w C o u p lin g
m a k e P a y m e n t(c a s h T e n d e re d ) 1 : m a k e P a y m e n t(c a s h T e n d e re d )
:R e g is te r :S a le
1 .1 : c re a te (c a s h T e n d e re d )
:P a y m e n t
68
e n d S a le ( ) :R e g is te r 1 : b e c o m e C o m p le te ( ) s :S a le
b y C o n tr o lle r b y E x p e rt
69
b y E x p e rt b y E x p e rt
to t := g e tT o ta l( ) :S a le 1 * : s t := g e tS u b to ta l( ) : S a le s L in e Ite m
*
1 .1 : p r := g e tP r ic e ( )
r e c a ll th is s p e c ia l n o ta tio n t o
in d ic a t e it e r a tio n o v e r th e : P r o d u c tS p e c ific a tio n
e le m e n ts o f a c o lle c tio n
70
n o t e t h a t t h e S a le in s ta n c e is n a m e d
's ' s o t h a t it c a n b e r e f e r e n c e d a s a
p a r a m e te r in m e s s a g e s 2 a n d 2 .1
m a k e P a y m e n t(c a s h T e n d e re d ) 1 : m a k e P a y m e n t(c a s h T e n d e re d )
: R e g is te r s :S a le
2 : a d d S a le ( s ) 1 .1 : c re a te (c a s h T e n d e re d )
b y E x p e rt
:P a y m e n t
:S to re
2 .1 : a d d (s )
c o m p le t e d S a le s : S a le
c o m p le t e d S a le s : S a le
71
b y C re a to r
b y C o n tr o lle r
e n te r I te m ( id , q ty ) 2 : m a k e L in e Ite m ( s p e c , q t y )
:R e g is t e r : S a le
1 : s p e c : = g e tS p e c ific a tio n ( id )
2 .1 : c re a te (s p e c , q ty )
:P ro d u c t
b y E x p e rt
C a ta lo g
s l: S a le s L in e I te m
1 .1 : s p e c := f in d ( id )
2 . 2 : a d d ( s l)
T h is f in d m e s s a g e is to t h e
M a p o b je c t ( th e m u ltio b je c t) , S a le s L in e Ite m a d d t h e n e w ly c r e a t e d
:P ro d u c t : S a le s L in e I te m
n o t t o a P r o d u c t S p e c if ic a t io n . S p e c ific a t io n S a le s L in e I te m in s ta n c e t o t h e
m u lt io b je c t ( e .g . , L is t )
C AU T IO N :
C A U T IO N :
T h is is a m u lt io b je c t c o lle c tio n ( s u c h a s a M a p ) , n o t a
T h is is a m u lt io b je c t c o lle c t io n ( s u c h a s a L is t ) , n o t a
P ro d u c t S p e c if ic a t io n . It m a y c o n t a in m a n y
S a le s L in e I te m . It m a y c o n ta in m a n y S a le s L in e It e m s .
P ro d u c t S p e c if ic a t io n s .
72
b y C re a to r
m a k e C h e c k P a y m e n t ( d r iv e r s L ic e n s e N u m )
1:
: R e g is t e r m a k e C h e c k P a y m e n t ( d r iv e r s L ic e n s e N u m ) :S a le
1 . 1 : c r e a t e ( d r iv e r s L ic e n s e N u m , t o ta l)
1 .2 : a u th o r iz e ( )
b y D o It M y s e lf a n d P o ly m o r p h is m
:D r iv e r s L ic e n s e :C h e c k P a y m e n t
1 .1 .1 :
c r e a t e ( d r iv e r s L ic e n s e N u m )
:C h e c k
1 .1 .2 :
c r e a te ( to ta l)
b y C re a to r
73
b y C re a to r
m a k e C r e d itP a y m e n t( c c N u m , e x p ir y D a te )
1:
:R e g is te r m a k e C r e d itP a y m e n t( c a r d N u m e x p ir y D a te ) : S a le
1 . 1 : c r e a t e ( c c N u m , e x p ir y D a t e , t o ta l)
b y D o I t M y s e lf a n d P o ly m o r p h is m 1 . 2 : a u th o r iz e ( )
:C r e d itC a r d :C r e d itP a y m e n t
1 .1 .1 :
c r e a t e ( c c N u m , e x p ir y D a t e )
b y C re a to r
74
S a le S a le
... ...
... ...
* *
L o g s - c o m p le te d L o g s - c o m p le te d
1 1
S to re S a le s L e d g e r
... ...
a d d S a le ( s : S a le ) a d d S a le ( s : S a le )
... ...
S to r e is r e s p o n s ib le fo r
S a le s L e d g e r is r e s p o n s ib le
k n o w in g a n d a d d in g
f o r k n o w in g a n d a d d in g
c o m p le te d S a le s .
c o m p le t e d S a le s .
A c c e p ta b le in e a r ly
S u ita b le w h e n th e d e s ig n
d e v e lo p m e n t c y c le s if th e
g ro w s a n d th e S to re
S to re h a s fe w
b e c o m e s u n c o h e s iv e .
r e s p o n s ib ilitie s .
75
S to re
1 a d d re s s : A d d re s s 1
1
n a m e : Te xt
P r o d u c tS p e c ific a tio n
P r o d u c tC a ta lo g
a d d S a le ( )
d e s c r ip t io n : T e x t
p r ic e : M o n e y
1 1 1 1 ..* ite m I D : Ite m ID
g e tS p e c ific a tio n ( )
1
1 1 S a le
R e g is te r d a te : D a te
*
is C o m p le te : B o o le a n S a le s L in e Ite m
tim e : T im e
q u a n tity : In te g e r
e n d S a le ( ) 1 1 1 1 ..*
b e c o m e C o m p le te ( )
e n te r Ite m () g e t S u b t o t a l( )
m a k e L in e Ite m ( )
m a k e N e w S a le ( )
m a k e P a y m e n t()
m a k e P a y m e n t()
g e tT o ta l( )
1
* P aym ent
am ount : M oney
1
76