0% found this document useful (0 votes)
58 views

Chapter 3 1 DesignPattern PDF

The document discusses design patterns and principles for assigning responsibilities between classes in object-oriented design. It defines patterns such as Expert, Creator, and Low Coupling. The Expert pattern assigns a responsibility to the class that has the necessary information to fulfill it. The Creator pattern assigns the responsibility of object creation to the class that aggregates or contains the object. The Low Coupling pattern aims to assign responsibilities so that dependencies between classes remain low.

Uploaded by

Sawn Hot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views

Chapter 3 1 DesignPattern PDF

The document discusses design patterns and principles for assigning responsibilities between classes in object-oriented design. It defines patterns such as Expert, Creator, and Low Coupling. The Expert pattern assigns a responsibility to the class that has the necessary information to fulfill it. The Creator pattern assigns the responsibility of object creation to the class that aggregates or contains the object. The Low Coupling pattern aims to assign responsibilities so that dependencies between classes remain low.

Uploaded by

Sawn Hot
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 80

References:

• Applying UML and patterns


Craig Larman

1
2
What are patterns?

• Principles and solutions codified in a


structured format describing a problem and
a solution
• A named problem/solution pair that can be
applied in new contexts
• It is advice from previous designers to help
designers in new situations

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

t := total() :Sale Sale

date
time

New method total()

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.

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()
15
Expert : Example

Hence responsibilities assign to the 3 classes.

Class Responsibility

Sale knows sale total

SalesLineItem knows line item subtotal

ProductSpecification knows product price

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

who has responsibility to create an object?


By creator, assign class B responsibility of creating instance of class A if

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

where there is a choice, prefer


B aggregates or contains A objects

19
Creator : Example

Who is responsible for creating SalesLineItem objects?


Look for a class that aggregates or contains SalesLineItem objects.

Sale

date
time

Contain
s
1..*
Product
Sales Specification
LineItem * Described-
by description
quantity price
UPC

20
Creator : Example

Creator pattern suggests Sale.

Collaboration diagram is

makeLineItem(quantity) :Sale Sale

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

How can we make classes independent of other classes?

changes are localised


easier to understand
easier to reuse

Who has responsibility to create a payment?

Payment POST Sale

26
Low Coupling
Two possibilities:

1. Post makePayment() :POST 1: create() p : Payment

2: addPayment(p)
:Sale

makePayment() 1: makePayment()
2. Sale :POST :Sale

1.1. create()

:Payment

Low coupling suggests Sale because Sale has to be coupled


to Payment anyway (Sale knows its total).
27
High Cohesion
Problem:
To keep complexity manageable?
Solution:
Assign responsibilities so that cohesion
remains high.

28
Some examples:

• Very Low Cohesion: A Class is solely responsible for


many things in very different functional areas
• Low Cohesion: A class has sole responsibility for a
complex task in one functional area.
• High Cohesion. A class has moderate responsibilities in
one functional area and collaborates with classes to fulfil
tasks.

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

Who has responsibility to create a payment?

1.Post

makePayment() :POST 1: create() p : Payment

2: addPayment(p)
:Sale

looks OK if makePayement considered in isolation, but


adding more system operations, Post would take on more and
more responsibilities and become less cohesive.

31
High Cohesion
Giving responsibility to Sale supports higher cohesion in Post, as well as
low coupling.

makePayment() :POST 1: makePayment() :Sale

1.1. create()

:Payment

This design supports low coupling and high cohesion so it is desirable

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

By controller, we have 4 choices


enterItem(upc, quantity)
:POST
the overall system Post
the overall business Store enterItem(upc, quantity) :Store

someone in the real world


enterItem(upc, quantity)
who is active in the task Cashier :Cashier

an artificial handler of all system


enterItem(upc, quantity) :BuyItemsHandler
events of a use case BuyItemsHandler

The choice of which one to use will be influenced by


other factors such as cohesion and coupling
37
38
Good design
- presentation layer decoupled from problem domain
Object Store

UPC Quantity

Total

Tendered Balance

presses button
Enter Item End Sale Make Payment

Cashier

onEnterItem()

Presentation Layer system event message


:POSTCommand
(Command Object)

1: enterItem(upc, qty)

controller

Domain Layer 1.1: makeLineItem(upc, qty)


:POST :Sale

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

It is undesirable for a presentation


layer objects such as a Java applet to
Presentation Layer
:POSTCommand get involved in deciding how to handle
(Command object) domain processes.

Business logic is embedded in the


presentation layer, which is not useful.

1: makeLineItem(upc, qty)
Domain Layer :Sale

POSTApplet should not


send this message.

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

CashPayment CreditPayment CheckPayment

authorize() authorize() authorize()

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

By Pure Fabrication PersistentStorageBroker

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

The Pure fabrication example of de-coupling the Sale from


the relational database services through the introduction of
a PersistentStorageBroker is also an example of assigning
responsibilities to support Indirection. The
PersistentStorageBroker acts as a intermediary between
the Sale and database

52
Indirection : Example

By Indirection Modem

dial( )
receive( )
send( )

Modem::dial(phoneNum)
{
::OS_OpenPort(1);
::OS_Dial(phoneNUM)
}

authorize(payment) CreditAuthorizationService 1:dial(phoneNum) Modem

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:

• The this object (or self)


• A parameter of the method
• An attribute of self
• An element of a collection which is an attribute of self
• An object created within the method

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

:POST 1:prnt:=payment() : payment


amt:=paymentAmount():Float :Sale

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

:POST 1:prnt:=payment() : payment


amt:=paymentAmount():Float :Sale

1.1:amt:=amountTendered():Float

prnt:Payment

Supports the Law of


Demeter

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

Sale 1 1..* Sales


...
LineItem
date
...
... quantity

the domain objects, attributes, and


domain objects associations that undergo state changes
Use-Case 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

use-case Design Model


realization
: Register : ProductCatalog

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

tot := getTotal() :Sale 1 *: st := getSubtotal() : SalesLineItem


*
1.1: pr := getPrice()

recall this special notation to


indicate iteration over the :ProductSpecification
elements of a collection

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

2: addSale(s) 1.1: create(cashTendered)

by Expert
:Payment
:Store

2.1: add(s)

completedSales: Sale
completedSales: Sale

75
by Creator
by Controller

enterItem(id, qty) 2: makeLineItem(spec, qty)


:Register :Sale

1: spec := getSpecification(id)
2.1: create(spec, qty)

:Product
by Expert
Catalog

sl: SalesLineItem
1.1: spec := find(id)
2.2: add(sl)

This find message is to the


Map object (the multiobject), SalesLineItem add the newly created
:Product :SalesLineItem
not to a ProductSpecification. Specification SalesLineItem instance to the
multiobject (e.g., List)

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.1: create(driversLicenseNum ,total)

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)

by Do It Myself and Polymorphism 1.2: authorize()

:CreditCard :CreditPayment
1.1.1:
create (ccNum,expiryDate)

by Creator

78
Sale Sale

... ...

... ...

* *
Logs-completed Logs-completed

1 1

Store SalesLedger

... ...

addSale(s : Sale) addSale(s : Sale)


... ...

Store is responsible for


SalesLedger is responsible
knowing and adding
for knowing and adding
completed Sales.
completed Sales.
Acceptable in early
Suitable when the design
development cycles if the
grows and the Store
Store has few
becomes uncohesive.
responsibilities.

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

You might also like