Chapter 3 1 DesignPattern PDF
Chapter 3 1 DesignPattern PDF
1
2
What are patterns?
3
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.
4
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)
5
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
6
Types of Design Pattern
7
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.
8
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 .
9
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.
10
GRASP patterns
General Responsibility Assignment Software Patterns
• Expert
• Creator
• Low Coupling
• High Cohesion
• Controller
• Polymorphism
• Pure Fabrication
• Indirection
• Protected Variations
• Law of Demeter 11
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.
12
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
13
Expert : Example
Need all SalesLineItem instances and their subtotals. Only Sale knows
this, so Sale is the information expert.
Hence
date
time
14
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.
SalesLineItem
sli:SalesLineItem :SalesLineItem
SalesLineItem
quantity
2.1: p := price()
subtotal()
:Product Product
Specification Specification
description
price
UPC
New method price()
15
Expert : Example
Class Responsibility
16
Expert
• Maintain encapsulation of information
• Promotes low coupling
• Promotes highly cohesive classes
• Can cause a class to become excessively
complex
17
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.
18
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
19
Creator : Example
Sale
date
time
Contain
s
1..*
Product
Sales Specification
LineItem * Described-
by description
quantity price
UPC
20
Creator : Example
Collaboration diagram is
date
time
1: create(quantity) New method
makeLineItem()
total()
:SalesLineItem
21
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
22
Low Coupling
Problem:
To support low dependency and increased
reuse?
Solution:
Assign responsibilities so that coupling
remains low.
23
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.
24
Low coupling
• Classes are easier to maintain
• Easier to reuse
• Changes are localised
25
Low Coupling
26
Low Coupling
Two possibilities:
2: addPayment(p)
:Sale
makePayment() 1: makePayment()
2. Sale :POST :Sale
1.1. create()
:Payment
28
Some examples:
29
High cohesion
• Classes are easier to maintain
• Easier to understand
• Often support low coupling
• Supports reuse because of fine grained
responsibility
30
High Cohesion
1.Post
2: addPayment(p)
:Sale
31
High Cohesion
Giving responsibility to Sale supports higher cohesion in Post, as well as
low coupling.
1.1. create()
:Payment
32
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.
33
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).
34
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.
35
Controller : Example
System events in Buy Items use case
enterItem()
endSale()
makePayment()
who has the responsibility for enterItem()?
36
Controller : Example
UPC Quantity
Total
Tendered Balance
presses button
Enter Item End Sale Make Payment
Cashier
onEnterItem()
1: enterItem(upc, qty)
controller
39
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
40
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
41
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.
42
Polymorphism : Example
Payment
amount
By Polymorphism, each
payment should
authorize itself
43
Example : Polymorphism
44
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
45
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.
46
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.
47
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.
48
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
49
Pure Fabrication
• Preserves low coupling and high cohesion
of classes
• Improve reusability of classes
50
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.
51
Example : PersistentStorageBroker
52
Indirection : Example
By Indirection Modem
dial( )
receive( )
send( )
Modem::dial(phoneNum)
{
::OS_OpenPort(1);
::OS_Dial(phoneNUM)
}
53
• Assume that :
- A point-of-sale terminal application needs to manipulate a modem in order to
transmit credit payment request
- The operating system provides a low-level function call API for doing so.
- A class called CreditAuthorizationService is responsible for talking to the modem
• If CreditAuthorizationService invokes the low –level API function calls directly,
it is highly coupled to the API of the particular operating system. If the class
needs to be ported to another operating system, then it will requiure modification.
• Add an intermediate Modem class between the CreditAuthorizationService and
the modem API. It is responsible for translating abstract modem requests to the
API and creating an Indirection between the CreditAuthorizationService and the
modem .
54
Indirection
• Low coupling
• Promotes reusability
55
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.
56
Law of Demeter
It states that within a method, messages should only be sent to
the following objects:
57
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
58
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
59
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
60
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
61
Law of Demeter – Time totalling example
62
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.
63
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.
64
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
65
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.
66
Good time-totalling collaboration
67
Law of Demeter – Time totalling example with added operations
68
Sample UP Artifact Relationships for Use-Case Realization
Domain Model
: System
Process Sale Operation: makeNewSale
: Cashier make
1. Customer NewSale() Post-conditions:
arrives ... -...
2. Cashier system system
makes new enterItem
events operations
sale. (id, quantity)
conceptual 3. Cashier Operation: enterItem
classes in enters item
the identifier. endSale()
Post-conditions:
domain 4.... - A SalesLineItem instance
inspire the sli was created
names of makePayment -...
some (amount)
software
classes in Use Cases System Sequence Diagrams Contracts
the design in addition to the use
cases, requirements that
some ideas and inspiration for the post- must be satisfied by the
conditions derive from the use cases design of the software
makeNewSale()
create()
enterItem : Sale
(itemID, quantity)
spec := getSpecification( itemID )
addLineItem( spec, quantity )
...
endSale()
... ... 69
by Creator
and
Controller Register creates a
Sale by Creator by Creator, Sale
:Register creates an empty
multiobject (such as
a List) which will
eventually hold
SalesLineItem
instances
makeNewSale()
create() :Sale
create() :Sales
LineItem
CAUTION:
this activation is implied to be within the This is not a SalesLineItem instance. This is
constructor of the Sale instance a collection object (such as a List) that can
hold SalesLineitem objects.
70
by Controller
:Register
makeNewSale()
71
by Controller by Creator and Low Coupling
makePayment(cashTendered) 1: makePayment(cashTendered)
:Register :Sale
1.1: create(cashTendered)
:Payment
72
endSale() 1: becomeComplete()
:Register s :Sale
by Controller by Expert
73
by Expert by Expert
74
note that the Sale instance is named
's' so that it can be referenced as a
parameter in messages 2 and 2.1
makePayment(cashTendered) 1: makePayment(cashTendered)
:Register s :Sale
by Expert
:Payment
:Store
2.1: add(s)
completedSales: Sale
completedSales: Sale
75
by Creator
by Controller
1: spec := getSpecification(id)
2.1: create(spec, qty)
:Product
by Expert
Catalog
sl: SalesLineItem
1.1: spec := find(id)
2.2: add(sl)
CAUTION:
CAUTION:
This is a multiobject collection (such as a Map), not a
This is a multiobject collection (such as a List), not a
ProductSpecification. It may contain many
SalesLineItem. It may contain many SalesLineItems.
ProductSpecifications.
76
by Creator
makeCheckPayment(driversLicenseNum )
1:
:Register makeCheckPayment(driversLicenseNum ) :Sale
1.2: authorize()
by Do It Myself and Polymorphism
:DriversLicense :CheckPayment
1.1.1:
create (driversLicenseNum )
:Check
1.1.2:
create(total)
by Creator
77
by Creator
makeCreditPayment(ccNum,expiryDate)
1:
:Register makeCreditPayment(cardNum expiryDate) :Sale
1.1: create(ccNum,expiryDate,total)
:CreditCard :CreditPayment
1.1.1:
create (ccNum,expiryDate)
by Creator
78
Sale Sale
... ...
... ...
* *
Logs-completed Logs-completed
1 1
Store SalesLedger
... ...
79
Store
1 address : Address 1
1
name : Text
ProductSpecification
ProductCatalog
addSale()
description : Text
price : Money
1 1 1 1..* itemID: ItemID
getSpecification()
1
1 1 Sale
Register date : Date
*
isComplete : Boolean SalesLineItem
time : Time
quantity : Integer
endSale() 1 1 1 1..*
becomeComplete()
enterItem() getSubtotal()
makeLineItem()
makeNewSale()
makePayment()
makePayment()
getTotal()
1
* Payment
amount : Money
1
80