Skip to main content
UNIT IV - DESIGN PATTERNS
GRASP: Designing objects with responsibilities - Creator -
Information expert - Low Coupling - High Cohesion - Controller.
Design Patterns: creational: factory method - structural:
Bridge, Adapter - behavioural: Strategy, observer - Applying
GoF design patterns - Mapping design to code.
OBJECT ORIENTED ANALYSIS AND DESIGN
CS8592
Design patterns in architecture
 A pattern is a recurring solution to a standard problem.
 “A pattern describes a problem
which occurs over and over again
in our environment, and then
describes the core of the solution
to that problem, in such a way that
you can use this solution a million
times over, without ever doing it
the same way twice.”
2
Patterns in engineering
 How do engineers find and use patterns?
 Mature engineering disciplines have handbooks
describing successful solutions to known problems
 Automobile designers don't design cars from scratch
using the laws of physics
 Instead, they reuse standard designs with successful
track records, learning from experience
 Should software engineers make use of patterns? Why?
 Developing software from scratch is also expensive
 Patterns support reuse of software architecture design
3
Pattern in OO Design
 A pattern is a named description of a problem and
solution that can be applied in new contexts
 A pattern advises us on how to apply the solution in
varying circumstances and considers the forces and
trade-offs
4
What is a software pattern?
 A design pattern is a general reusable and proven solution to a
commonly occurring problem in software design.
 “ A pattern is a named problem/solution pair that can be
applied in new contexts, with advice on how to apply it in
novel situations”
5
Software pattern
5
GRASP = General Responsibility Assignment Software
Patterns
Describe fundamental principles for assigning
responsibilities to classes and for designing
interactions between classes
GoF: Gang of Four Design Patterns : 23 pattrens
Well known Pattern Families
6
GRASP
 Name chosen to suggest the importance of grasping
fundamental principles to successfully design object-
oriented software
 Describe fundamental principles of
object design and responsibility
 Expressed as patterns
7
“Identify requirements, create a domain model and define dynamic
behaviour , define messages to meet requirements , add methods to
the software classes …”
Too Simple!
 How do we assign responsibilities to classes?
 What methods belong where?
GRASP : Designing Objects With Responsibilities
8
 Design of behavior implies assigning responsibilities to software
classes.
 Responsibilities are assigned to classes of objects during object design.
 Responsibility is a contract or obligation of a class
 What must a class “know”? [knowing responsibility]
 What must a class “do”? [doing responsibility]
Responsability Driven Design-RDD
9
 What must a class “do”? [doing responsibility]
 Take action (create an object, do a calculation)
 Initiate action in other objects
 Control/coordinate actions in other objects
 Doing responsibilities are implemented by means of methods
 Methods fulfill responsibilities alone or through collaboration with
other objects and methods.
Ex: A Sale is responsible for creating SalesLineItems” (doing)
Doing Responsibility
10
: Sale
makePayment(cashTendered)
: Payment
create(cashTendered)
abstract, implies Sale objects have a
responsibility to create Payments
 Sale objects are given a responsibility to create Payments.
 The responsibility is invoked with a makePayment message.
Responsibilities and methods : create
11
 What must a class “know”? [knowing responsibility]
 Private encapsulated data
 Related objects
 Things it can derive or calculate
 Knowing responsibilities are related to attributes, associations in the
domain model.
 Domain model illustrates attributes and associations => inspires the
“knowing” responsibilities.
Ex : a Sale is responsible for knowing its total” (knowing)
Knowing Responsibility
12
:Book
d := getDueDate()
getDueDate message implies
Book has responsibility for
knowing its due date.
Responsibilities and attribute
13
 Responsibilities are implemented by methods
 Some methods act alone and do a task
 Some collaborate with other objects to fulfill their responsibility.
Example:
Sale class has getTotal() method, the getTotal() collaborates with
SalesLineItem objects to get the subtotal through getSubtotal()
methods.
RDD and Collaboration
14
9 GRASP patterns
• Creator
• Information Expert
• Low Coupling
• High Cohesion
• Controller
• Polymorphism
• Pure Fabrication
• Indirection
• Don’t Talk to Strangers (Protected Variations)
GRASP Patterns
15
 Problem: Who creates an A object
 Solution: Assign class B the responsibility to create an
instance of class A if one of these is true
• B “contains or aggregate ” A
• B “records” A
• B “closely uses” A
• B “ has the Initializing data for ” A
Creator principle
16
B “has the Initializing data for ” A that will be passed to A when it is
created.
Often initiation is done using a constructor with parameters.
e.g. a Payment instance, when created
needs to be initialized with the Sale total.
Sale class knows Sale total. Good candidate for creating Payment
is Sale.
If more than one of the above applies, prefer a class B which
aggregates or contains A.
Creator principle
17
Creator Pattern in Monopoly
18
Sale
time
Sales
LineItem
quantity
Product
Description
description
price
itemID
Described-by
*
Contains
1..*
1
1
Problem : Who should create a SalesLineItem?
19
20
Problem : Who should create a SalesLineItem?
20
: Register : Sale
makeLineItem(quantity)
: SalesLineItem
create(quantity)
 Sale objects are given a responsibility to create SaleLineItem.
 The responsibility is invoked with a makeLineItem message
Creating a SalesLineItem
21
22
Creating a SalesLineItem
22
Problem : What is a basic principle by which to assign
responsibilities to objects?
Solution (advice ) : Assign a responsibility to the information
expert , that is the class with the information necessary to
fulfill the responsibility.
“Objects do things related to the information they have.”
Information Expert
23
Start assigning responsibilities by clearly stating the
responsibility.
• Who should be responsible for knowing the grand
total of a sale?
Applying Expert in POS Application
24
Sale
time
Sales
LineItem
quantity
Product
Description
description
price
itemID
Described-by
*
Contains
1..*
1
1
Who should responsible for knowing the grand total of a
sale?
25
26
Who should responsible for knowing the grand total of a
sale?
26
Sale
time
...
getTotal()
:Sale
t = getTotal
New method
 Add a Sale class to the Design Model.
 Express responsibility of knowing the total of a sale with the method named getTotal.
• What information do we need to know to determine the line item subtotal?
Sale knows about neighbours (associations), SaleLineitems who is responsible for
knowing its subtotal
Partial interaction and class diagrams
27
Sale
time
...
getTotal()
SalesLineItem
quantity
getSubtotal()
New method
1 *: st = getSubtotal
: Sale
t = getTotal lineItems[ i ] :
SalesLineItem
this notation will imply we
are iterating over all
elements of a collection
• How does the SalesLineItem find out the product price?
SaleLineItem knows about neighbours ( ProductDescription) to get the price.
SalesLineItem is Expert for Subtotal
28
Sale
time
...
getTotal()
SalesLineItem
quantity
getSubtotal()
Product
Description
description
price
itemID
getPrice()
New method
:Product
Description
1.1: p := getPrice()
1 *: st = getSubtotal
: Sale
t = getTotal lineItems[ i ] :
SalesLineItem
“Partial” information experts collaborate to fulfill the responsibility.
ProductDescription is Expert for Price
29
30
Problem:
How to support low dependency, Low change impact, and
increased reuse?
Solution: Assign responsibilities so that coupling remains
low. Use this principle to evaluate alternatives.
Coupling is a measure of how strongly one class is
• connected to,
• has knowledge of, or
• relies upon other classes.
“Low Coupling” Principle
30
 Coupling between classes is dependency of one class on
another class
 Common form of coupling from Class A to Class B are:
 Class A has an attribute (data member or instance variable)
that refers to a Class B instance, or Class B itself.
What is a coupling ?
31
 What class should be responsible for creating a Payment
instance and associating it with the Sale?
 Register?
 Sale?
 Creator pattern suggests Register should create the Payment.
 A register records a payment in the real world.
Low Coupling - POS Case Study
32
: Register p: Payment
:Sale
makePayment() 1: create()
2: addPayment(p)
Register is coupled to both Sale and Payment.
What if Register creates Payment?
33
: Register :Sale
:Payment
makePayment() 1: makePayment()
1.1. create()
 Assuming that the Sale must eventually be coupled to knowledge
of a Payment, having Sale create the Payment does not increase
coupling.
What if Sale creates Payment ?
34
A class with low cohesion does too much unrelated work and are:
• Hard to comprehend
• Hard to reuse
• Hard to maintain
• Delicate and constantly affected by change
Cohesion is a measure of how strongly related the responsibilities of an
element (classes, subsystems).
High Cohesion
35
 Problem
 How to keep complexity manageable?
 Solution
 Assign a responsibility so that cohesion remains high
High Cohesion
36
: Register : Sale
addPayment( p )
p : Payment
create()
makePayment()
Low cohesion:
Register is taking part of the responsibility for fulfilling “makePayment” operation and
many other unrelated responsibility ( 50 system operations all received by Register) then
it will become burden with tasks and become incohesive.
Reduced cohesion of Register(creator pattern)
37
: Register : Sale
makePayment()
: Payment
create()
makePayment()
Solution:
Delegate the payment creation responsibility to “Sale” to support high cohesion
Higher Cohesion and Lower Coupling
38
UI layer does not contain any business logic
Problem:
How to connect UI layer to the business logic layer?
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.
Controller Pattern
39
What first object beyond the UI layer receives and
coordinates (“controls”) a system operation
message?
 Solution: Assign the responsibility to a class that
represents one of the following options:
Controller Pattern
40
1. Represents the overall system or a root object.
e.g., an object called System or Register
Suitable when there are not too many system events
or when UI cannot choose between multiple controllers.
2. A controller for each use case
e.g. processSaleHandler
Options for Control Responsibility
41
:R egister
enterItem (id , qua ntity)
:P ro cessS aleH andler
enterItem (id , qua ntity)
 Register (POS Terminal) is a specialized device with
software running on it.
 ProcessSaleHandler represents a receiver of all system
events of a use case scenario.
Controllers
Controller choices ?
42
Which class of object should be responsible for receiving this
system event message?
It is sometimes called the controller or coordinator. It does not
normally do the work, but delegates it to other objects.
The controller is a kind of "facade" onto the domain layer from
the interface layer.
actionPerformed( actionEvent )
: ???
: Cashier
:SaleJFrame
presses button
enterItem(itemID, qty)
UI Layer
Domain
Layer
system operation message
What should be Controller for enterItem?
43
C a sh ie r
:S a le JF ra m e
a ctio n P e rfo rm e d ( a ctio n E ve n t )
:S a le
1 : m a ke L in e Ite m (ite m ID , q ty)
U I L a y e r
D o m a in L a y e r
It is u n d e sira b le fo r an in te rfa ce
la ye r o b je ct su ch a s a w in d o w to g e t
in vo lve d in d e cid in g h o w to ha n d le
d o m ain p ro ce sse s .
B u sine ss lo g ic is e m b e d d e d in th e
p re sen ta tio n la ye r, w h ich is n o t u se fu l.
S a le JF ra m e sh o u ld n o t
se n d th is m e ssa g e .
p re sse s b u tto n
Bad Design
44
actionPerformed( actionEvent )
:Register
: Cashier
:SaleJFrame
presses button
1: enterItem(itemID, qty)
:Sale
1.1: makeLineItem(itemID, qty)
UI Layer
Domain Layer
system operation message
controller
Controller should delegate the work that needs to be done to other objects.
Good Design
45
Design patterns
 A pattern is a recurring solution to a standard problem, in a context.
 Christopher Alexander, a professor of architecture…
 Why would what a prof of architecture says be relevant to software?
 “A pattern describes a problem which occurs over and over again in our environment, and
then describes the core of the solution to that problem, in such a way that you can use this
solution a million times over, without ever doing it the same way twice.”
 Jim Coplein, a software engineer:
What are dress patterns?
 “I could tell you how to make a dress by specifying the route of a scissors through a piece
of cloth in terms of angles and lengths of cut. Or, I could give you a pattern. Reading the
specification, you would have no idea what was being built or if you had built the right thing
when you were finished. The pattern foreshadows the product: it is the rule for making the
thing, butitis also, in many respects, the thing itself.”
46
Uses of Design Patterns
 Finding appropriate objects.
 Determining object granularity.
 Specifying object interfaces.
 Specifying object implementations.
 Programming to an interface not to an
implementation.
47
The “gang of four” (GoF)
 Erich Gamma
 Richard Helm
 Ralph Johnson
 John Vlissides
 Design Patterns - 23 different patterns as solutions to different
classes of problems, in C++ & Smalltalk
48
Elements of Design Patterns
 Design patterns have 4 essential elements:
 Pattern name: increases vocabulary of designers
 Problem: intent, context, when to apply
 Solution: UML-like structure, abstract code
 Consequences: results and tradeoffs
49
Three Types of Patterns
 Creational patterns:
 Deal with initializing and configuring classes and objects
 Structural patterns:
 Deal with decoupling interface and implementation of classes and
objects
 Composition of classes or objects
 Behavioral patterns:
 Deal with dynamic interactions among societies of classes and
objects
 How they distribute responsibility
50
Creational Patterns
 Abstract Factory:
 Factory for building related objects
 Builder:
 Factory for building complex objects incrementally
 Factory Method:
 Method in a derived class creates associates
 Prototype:
 Factory for cloning new instances from a prototype
 Singleton:
 Factory for a singular (sole) instance
51
Structural Patterns
 Adapter:
 Translator adapts a server interface for a client
 Bridge:
 Abstraction for binding one of many implementations
 Composite:
 Structure for building recursive aggregations
 Decorator:
 Decorator extends an object transparently
 Facade:
 Simplifies the interface for a subsystem
 Flyweight:
 Many fine-grained objects shared efficiently.
 Proxy:
 One object approximates another
52
Behavioral Patterns
 Observer:
 Dependents update automatically when subject changes
 State:
 Object whose behavior depends on its state
 Strategy:
 Abstraction for selecting one of many algorithms
 Template Method:
 Algorithm with some steps supplied by a derived class
 Visitor:
 Operations applied to elements of a heterogeneous object structure
53
Behavioral Patterns (cont.)
 Chain of Responsibility:
 Request delegated to the responsible service provider
 Command:
 Request or Action is first-class object, hence re-storable
 Iterator:
 Aggregate and access elements sequentially
 Interpreter:
 Language interpreter for a small grammar
 Mediator:
 Coordinates interactions between its associates
 Memento:
 Snapshot captures and restores object states privately
54
Purpose
Creational Structural Behavioral
Scope Class Factory Method Adapter Interpreter
Template Method
Object Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Facade
Proxy
Flyweight
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
GoF Design Pattern Categories
55
What are creational patterns?
 Design patterns that deal with object creation
mechanisms, trying to create objects in a manner suitable to
the situation
 Make a system independent of the way in which objects are
created, composed and represented
 Recurring themes:
 Encapsulate knowledge about which concrete classes the
system uses (so we can change them easily later)
 Hide how instances of these classes are created and put
together (so we can change it easily later)
56
Benefits of creational patterns
 Creational patterns let you program to an interface defined by
an abstract class
 That lets you configure a system with “product” objects that
vary widely in structure and functionality
 Example: GUI systems
InterViews GUI class library
Multiple look-and-feels
Abstract Factories for different screen components
57
Benefits of creational patterns
 Generic instantiation – Objects are instantiated without having to
identify a specific class type in client code (Abstract Factory, Factory)
 Simplicity – Make instantiation easier: callers do not have to write long
complex code to instantiate and set up an object (Builder, Prototype
pattern)
 Creation constraints – Creational patterns can put bounds on who
can create objects, how they are created, and when they are created
58
FACTORY METHOD (Class Creational)
 Factory Method is to creating objects as Template Method
is to implementing an algorithm.
 Factory Method makes a design more customizable and
only a little more complicated.
 Factory Methods are routinely specified by an architectural
framework, and then implemented by the user of the
framework.
59
FACTORY METHOD-Structure
60
Definition
 Product defines the interface for objects the factory
method creates.
 ConcreteProduct implements the Product interface.
 Creator(also refered as Factory because it creates the
Product objects) declares the method FactoryMethod,
which returns a Product object. May call the generating
method for creating Product objects
 ConcreteCreator overrides the generating method for
creating ConcreteProduct objects.
61
Example: Documents Application
62
FACTORY METHOD Structure
63
Example:
64
Factory Example
class 350Z implements Car; // fast car
class Ram implements Car; // truck
class Accord implements Car; // family car
Car fast = new 350Z(); // returns fast car
public class carFactory {
public static Car create(String type) {
if (type.equals("fast")) return new 350Z();
if (type.equals("truck")) return new Ram();
else if (type.equals(“family”) return new Accord();
}
}
Car fast = carFactory.create(“fast”); // returns fast car
Product
Factory Method
65
Structural Patterns
 Adapter:
 Translator adapts a server interface for a client
 Bridge:
 Abstraction for binding one of many implementations
 Composite:
 Structure for building recursive aggregations
 Decorator:
 Decorator extends an object transparently
 Facade:
 Simplifies the interface for a subsystem
 Flyweight:
 Many fine-grained objects shared efficiently.
 Proxy:
 One object approximates another
66
 Context/problem
 How to resolve incompatible interfaces or provide a
stable interface to similar components with different
interfaces?
 Solution
 Convert the original interface of a component into
another interface through an intermediate adapter
object.
Adapter
67
Adapter or Intermediary
Adapter is about creating an intermediary abstraction that
translates, or maps, the old component to the new system.
68
 Adapters use interfaces and polymorphism to add a level
of indirections to varying APIs in other components.
Client
AbstractClass
clientNameForRequiredMethod()
Adapter
clientNameForRequiredMethod()
{ adaptee. requiredMethod();}
adaptee
RequiredClass
requiredMethod()
The Adapter Pattern
69
 Target - defines the domain-specific interface that Client uses.
 Adapter - adapts the interface Adaptee to the Target interface.
 Adaptee - defines an existing interface that needs adapting.
 Client - collaborates with objects conforming to the Target interface.
Adapter Example
70
Example:
71
Example:
72
:Client
clientNameForRequiredMethod()
:AbstractClass :Adapter
RequiredMethod()
adaptee
:RequiredClass
Sequence Diagram for Adapter
73
Adapter functions as a wrapper or modifier of an existing
class. It provides a different or translated view of that class.
Wrapper Class:
74
Wrapper Class:
A wrapper class wraps (encloses) around a data type and gives it an object
appearance. 75
Bridge
● The bridge pattern is a design pattern used in software
engineering which is meant to "decouple an abstraction from
its implementation so that the two can vary independently".
● The bridge uses encapsulation, aggregation, and can use
inheritance to separate responsibilities into different classes.
● The bridge pattern is often implemented using the class
adapter pattern.
76
Structure of Bridge
 Abstraction (abstract class)
 defines the abstract interface
 maintains the Implementor reference.
 RefinedAbstraction (normal class)
 extends the interface defined by
• Abstraction
 Implementor (interface)
 defines the interface for implementation
classes
 ConcreteImplementor (normal class)
 implements the Implementor interface
77
Example:
78
Example:
 A household switch controlling lights, ceiling fans, etc. is an example of
the Bridge. The purpose of the switch is to turn a device on or off.
79
Behavioral Pattern
 Behavioral patterns are concerned with the assignment
of responsibilities between objects, or encapsulating
behavior in an object and delegating requests to it.
1. Strategy
2. Observer
80
Strategy:
 A Strategy defines a set of algorithms that can be used
interchangeably.
 Strategy is like Template Method except in its granularity.
 Strategy lets you change the guts of an object.
81
Strategy: Structure
 Strategy - defines an interface common to all supported algorithms. Context uses this interface
to call the algorithm defined by a ConcreteStrategy.
 ConcreteStrategy - each concrete strategy implements an algorithm.
 Context
 contains a reference to a strategy object.
 may define an interface that lets strategy accessing its data.
82
Structure:
83
Example:
Modes of transportation
to an airport is an
example of a Strategy.
84
Example: Robots Application
85
Observer Pattern
 The Observer defines a one-to-many relationship so that
when one object changes state, the others are notified and
updated automatically.
 Encapsulate the core (or common or engine) components
in a Subject abstraction, and the variable (or optional or
user interface) components in an Observer hierarchy.
86
Observer Pattern
87
Structure Definition:
 Observable - interface or abstract class defining the operations for
attaching and de-attaching observers to the client. In the GOF book this
class/interface is known as Subject.
 ConcreteObservable - concrete Observable class. It maintain the
state of the object and when a change in the state occurs it notifies the
attached Observers.
 Observer - interface or abstract class defining the operations to be
used to notify this object.
 ConcreteObserverA, ConcreteObserver2 - concrete Observer
implementations.
88
Structure:
89
Example: News Agency
90
Example:
91
Mapping Designs to Code
• Write source code for:
• Class and interface definitions
• Method definitions
• Work from OOA/D artifacts
• Create class definitions for Domain Class Diagrams (DCDs)
• Create methods from Interaction diagrams
• The interaction diagrams and design class diagrams
created during design provide some of the
necessary input for generating code.
92
Creating Class definitions from design class diagrams
• Basic class definitions can be written from the design class
diagrams.
• The following information can be extracted:
• Class name
• Attributes: name, type and access specifier
• Method: name, return type, parameters and their types, and its
access specifier
• Elaborate from associations to add reference attributes
93
Reference Attributes
94
An attribute that refers to another complex objects.
• Reference Attributes are suggested by associations and navigability in a class diagram.
• Example: A product specification reference on a Sales Line Item. So here we can use
product spec as a complex reference attribute to sales line item class.
Containers and Collections
95
• Where an object must maintain visibility to a group of other objects,
such as a group of Sales Line Items in a Sale, object-oriented languages
often use an intermediate container or collection.
• These will be suggested by a multiplicity value greater than one on a
class diagram.
Role Names
96
• Each end of an association is a role. Reference Attributes are often suggested by
role names.
(use role names as the names of reference attributes).
Collection classes
SalesLineItem
quantity : Integer
getSubtotal()
1..*
Sale
isComplete : Boolean
time : DateTime
becomeComplete()
makeLineItem()
makePayment()
getTtotal()
public class Sale
{
...
private List lineItems = new ArrayList();
}
A collection class is necessary to
maintain attribute visibility to all the
SalesLineItems.
lineItems
What collection class has been added to the design and why?
97
Example
public class SalesLineItem
{
private int quantity;
private ProductDescription description;
public SalesLineItem(ProductDescription desc, int qty) { ... }
public Money getSubtotal() { ... }
}
SalesLineItem
quantity : Integer
getSubtotal() : Money
ProductDescription
description : Text
price : Money
itemID : ItemID
...
1
description
98
Why implement from least-coupled to most-coupled?
SalesLineItem
quantity : Integer
getSubtotal()
ProductCatalog
...
getProductDesc(...)
ProductDescription
description : Text
price : Money
itemID : ItemID
...
Store
address : Address
name : Text
addSale(...)
Payment
amount : Money
...
1..*
1..*
Register
...
endSale()
enterItem(...)
makeNewSale()
makePayment(...)
Sale
isComplete : Boolean
time : DateTime
becomeComplete()
makeLineItem(...)
makePayment(...)
getTotal()
...
1
1
1
1
1
1
*
1
2
3
4
5
6
7
99
Creating methods from Interaction Diagrams
100
• Interaction Diagrams are used to specify methods.
• They give most of the details for what the method does.