2. 2
Books
Design Patterns : Elements of Reusable Object-Oriented Software
(1995)
(The-Gang-of-Four Book)
The-Gang-of-Four (GoF) - Gamma, Helm, Johnson , Vlissides
Analysis Patterns - Reusable Object Models (1997)
Martin Fowler
The Design Patterns Smalltalk Companion (1998)
Alpert, Brown & Woolf
3. UML class diagram recall
Concrete
Abstract
Interface
# private
* protected
+ public
static
# private()
* protected()
+ public()
abstract()
static()
name(Type1, Type2) :
RetType
code
3
Packag
e
Class1
Class2
ClassN
derived
aggregato
r
creator
caller/use
base
aggregate
e
product
callee/use
4. What is a Design Pattern?
A design pattern is a general reusable solution to
a commonly occurring problem in software design.
A design pattern is not a finished design that can
be transformed directly into code. It is a
description or template for how to solve a
problem that can be used in many different
situations.
Object-oriented design patterns typically show
relationships and interactions between classes
or objects, without specifying the final application
4
5. Why Design Patterns?
Design patterns support object-oriented reuse at a high level of
abstraction
Design patterns provide a “framework” that guides and constrains
object-oriented implementation
4 Essential Elements of Design Patterns
Name : identifies a pattern
Problem : describes when to apply the pattern in terms of the
problem and context
Solution : describes elements that make up the design, their
relationships, responsibilities, and collaborations
Consequences : results and trade-offs of applying the pattern
6. 6
Organizing Design Patterns
By Purpose (reflects what a pattern does):
• Creational Patterns
• Structural Patterns
• Behavioral Patterns
By Scope: specifies whether the pattern applies primarily to
classes or to
objects.
7. 7
Design Patterns Space
Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Façade
Flyweight
Proxy
Chain of
Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Factory Method Adapter
Interpreter
Template
Creational Structural Behavioral
Object
Class
Scope
Purpose
9. What are creational patterns?
Design patterns that deal with object creation mechanisms, trying
to create objects in a manner suitable to the situation. The
Creational pattern show how to make the software design
flexible.
There are 5 well known design patterns that are part of creational
pattern. These are-
Abstract Factory pattern – is for creating the instances of several
families of classes
Factory method pattern- is for creating the instances of several
derived classes
Singleton pattern: It ensures that a class has only one instance
and provides global point of access to it
Builder pattern- separates the object construction from its
representation
Prototype pattern- It specifies the kinds of objects to create using a
prototypical instance and create new objects by copying this
prototype.
10. 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
11. 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
12. Factory Method
Intent: The factory method pattern makes use of factory methods to deal
with the problem of creating objects without specifying the exact class
of the object that will be created.
The interface is defined for creating an object but the subclass decides
which class to instantiate
The advantage of a factory method is that it can return the same instance
multiple times, or can return a subclass rather than an object of that
exact type
Other design patterns require new classes whereas the factory method
only requires new operation
Using Factory method the design can be made customizable
14. Sample skeleton
Step1: the interface Product and the ConcreteProduct class is written as follows
Public interface Product
{ // body of interface }
Step2: The client class makes use of ConcereteFactory clss which creates the instance creator, and using this
instance or object the factoryMethod can be invoked in some function say-MyFunction. The
factoryMethod is useful for creating the product objects
Public abstract class Factory
{
protected abstract Product factoryMethod();
Public void myFunction()
{ Product product = factoryMethod(); }
}
Public class ConcreteFactory extends Factory
{
protected Product factoryMethod()
{ return new ConcreteProduct(); // returns object of ConcreteProduct class }
}
Public class Program
{
public static void main (String arg[])
{ Factory creator = new ConcreteFactory();
creator.myFuction();
}
}
15. Creational-Abstract Factory: An
Example
PIM system
Manage addresses and phone numbers
You hard-coded it for US data
At some point, you wanted to extend it to
incorporate any address / phone number
So you subclassed
DutchAddress, JapanesePhoneNumber, etc.
But now, how do you create them?
16. Creational-Abstract Factory:
Overview
Intent
Provide an interface for creating families of related or
dependent objects without specifying their concrete
classes
Analogous to a pasta maker
Your code is the pasta maker
Different disks create different pasta shapes:
these are the factories
All disks have certain properties in common
so that they will work with the pasta maker
All pastas have certain characteristics in
common that are inherited from the generic
“Pasta” object
17. Creational-Abstract Factory:
Participants
AbstractFactory
Declares an interface for operations
that create abstract products
ConcreteFactory
Implements the operations to create
concrete product objects: usually
instantiated as a Singleton
AbstractProduct
Declares an interface for a type of
product object; Concrete Factories
produce the concrete products
ConcreteProduct
Defines a product object to be created
by the corresponding concrete factory
18. Creational - Abstract Factory:
Applicability
Use Abstract Factory when:
A system should be independent of how its
products are created, composed, and
represented
A system should be configured with one of
multiple families of products
You want to provide a class library of products,
and you want to reveal just their interfaces, not
their implementations
19. Creational-Abstract Factory: Consequences
Good:
Isolates concrete classes
All manipulation on client-side done through abstract interfaces
Makes exchanging product families easy
Just change the ConcreteFactory
Enforces consistency among products
Bad
Supporting new kinds of products is difficult
Have to reprogram Abstract Factory and all subclasses
But it’s not so bad in dynamically typed languages
20. Creational-Abstract Factory:
Implementation
Usually should be a Singleton
Define a Factory Method (GoF) in AbstractFactory –
ConcreteFactory then specifies its products by
overriding the factory for each
public class USAddressFactory implements AddressFactory{
public Address createAddress(){
return new USAddress();
}
public PhoneNumber createPhoneNumber(){
return new USPhoneNumber();
}
}
Maybe use Prototype pattern in dynamically typed
languages (e.g. Smalltalk) to simplify creation
21. Creational-Factory Method
Define an interface for creating an object,
but let subclasses decide which class to
instantiate. Factory Method lets a class
defer instantiation to subclasses.
21
return new ConcreteProduct();
...
Product product =
CreateProduct();
...
23. 23
Structural Patterns
In software engineering, Structural Design patterns are design patterns that
ease the design by identifying a simple way to realize relationships between
entities
The structural design pattern serves as a blue print for how different classes and
objects are combined to form larger structures
Structural patterns are just similar to data structures
Composite
Adapter
Bridge
Façade
Proxy
24. 24
Structural Patterns - Adapter
Convert the interface of a class into another interface clients expect.
Adapter lets classes work together that couldn’t otherwise because of
incompatible interfaces.
Applicability
Reuse of an existing class is desired, but the interface does not
match the need.
Design of a reusable class that cooperates with unrelated or
unforeseen classes, but classes don’t have compatible interfaces.
Intent
25. 25
How to implement Adapter Design pattern
Client
Adapter
+request()
Adaptee
+specialOperation()
Target
+request()
adaptee.specificOperation()
<<interface>>
target
adaptee
Target — defines the domain-specific interface that the client uses.
Client — collaborates with objects conforming to the Target interface.
Adaptee — defines an existing interface that needs adapting.
Adapter — adapts the interface of Adaptee to the Target interface.
Participants
Clients call operations on an
Adapter instance. In turn, the
Adapter calls Adaptee
operations that carry out the
request.
Collaborations
• Client class makes use of Target interface so that it can just call the Request()
method of the Target interface.
• This Adapter class translates the request from the client to the adaptee. This class
translates incompatible interface of Adaptee into interface of Client.
• The Adaptee class provides the functionality that is required by the client
26. Structural -Adapter Pattern (26.1)
Problem: How to resolve incompatible interfaces, or
how to 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.
Note: the Adapter pattern is an application of
Polymorphism
27. Structural -Adapter Pattern (26.1)
Example: POS needs to adapt several kinds of
external third-party services: tax calculators,
credit authorization services, inventory
systems, accounting systems. Each has a
different API which can’t be changed.
28. Structural -Fig. 26.1
TaxMasterAdapter
getTaxes( Sale ) : List of TaxLineItems
GoodAsGoldTaxPro
Adapter
getTaxes( Sale ) : List of TaxLineItems
«interface»
ITaxCalculatorAdapter
getTaxes( Sale ) : List of TaxLineItems
Adapters use interfaces and
polymorphism to add a level of
indirection to varying APIs in other
components.
SAPAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
...
GreatNorthernAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
...
«interface»
IAccountingAdapter
postReceivable( CreditPayment )
postSale( Sale )
...
«interface»
IInventoryAdapter
...
«interface»
ICreditAuthorizationService
Adapter
requestApproval(CreditPayment,TerminalID, MerchantID)
...
29. Structural -Fig. 26.2
:Register : SAPAccountingAdapter
postSale( sale )
makePayment
the Adapter adapts to
interfaces in other components
SOAP over
HTTP
xxx
...
«actor»
: SAPSystem
30. Structural -Adapter Pattern (26.1)
Note: Adapter pattern follows GRASP
principles: Polymorphism, Protected
Variation, Indirection
See Fig. 26.3 for conceptual connection
among GRASP principles and Adapter
pattern
31. Structural- 26.3
Low coupling is a way to achieve protection at a
variation point.
Polymorphism is a way to achieve protection at a
variation point, and a way to achieve low coupling.
An indirection is a way to achieve low coupling.
The Adapter design pattern is a kind of Indirection
and a Pure Fabrication, that uses Polymorphism.
Protected Variation
Mechanism
Low Coupling
Mechanism
Indirection
Mechanism
Adapter
Pure
Fabrication
Polymorphism
Example
GoF Design
Patterns
GRASP
Principles
High Cohesion
Mechanism
32. Structural -Adapter Pattern
Definition
Convert existing interfaces to new interface
Where to use & benefits
Help match an interface
Make unrelated classes work together
Increase transparency of classes
33. Structural -Adapter Pattern
Example
Adapter from integer Set to integer Priority Queue
Original
Integer set does not support Priority Queue
Using pattern
Adapter provides interface for using Set as Priority
Queue
Add needed functionality in Adapter methods
34. Structural -Adapter Example
public interface PriorityQueue
{ // Priority Queue
void add(Object o);
int size();
Object removeSmallest();
}
35. Structural -Adapter Example
public class PriorityQueueAdapter implements PriorityQueue
{
Set s;
PriorityQueueAdapter(Set s) { this.s = s; }
public void add(Object o) { s.add(o); }
int size() { return s.size(); }
public Integer removeSmallest()
{
Integer smallest = Integer.MAX_VALUE;
Iterator it = s.iterator();
while ( it.hasNext() )
{
Integer i = it.next();
if (i.compareTo(smallest) < 0)
smallest = i;
}
s.remove(smallest);
return smallest;
}
}
36. Structural - Adapter
Convert the interface of a class into
another interface clients expect. Adapter
lets classes work together that couldn't
otherwise because of incompatible
interfaces.
36
_adaptee.SpecificRequest();
37. 37
Structural Patterns - Bridge
Intent:
The Bridge pattern separates or decouples the interface from
implementation without using inheritance
A parallel class hierarchy is used. On one side of the hierarchy there are
abstract interfaces and on the other side there are concrete
implementations
This pattern can be used when the class vary quite often. These changes
can be accommodated very easily without disturbing the rest of the code.
This is because of the fact that the implementation and separated one
38. 38
Structural Patterns – Bridge-Implementation
ConcreteImplementor
<<interface>>
Implementor
<<interface>>
Abstraction
Opr:
Function()
Refined Function()
Refined
Abstraction
operation()
operation()
Defines abstraction interface. Acts as a base
class for other refined classes. Holds the
reference to particular implementation which is
for platform specific functionality
Interface for the
ConcreteImplementor
Normal class which implements the
Implementor Interface.
Normal class which extends the
Interface defined by Abstraction
39. S.No
Bridge Adapter
1 The bridge pattern is used to decouple as
abstraction class from its implementation
The adapter pattern converts the interface
between classes with less inheritance
2 This patterns can be used when class vary quite
often
This pattern is often used to make existing
classes work with other without modifying their
source code
3 This pattern is used in graphics toolkits that need
to be run on different platforms
This pattern is used when two incompatible
interfaces need to work together
4 The situation in which class vary quite often, the
bridge pattern is used, Due to use of this pattern
the changes can be accommodated very easily
without distributing the rest of the code as the
implementation and interfaces are separated one
The situation in which one class relies upon a
specific interface which is not implemented by
another class, the adapter acts as a translator
between two types
5 The implementation details can be effectively
hidden from the client so that the client can focus
on the behavior desired from the abstraction
If we have several modules implementing the
same functionality and we wrote the adapters
for them, the adapters are implementing the
same interface. 6
6 Due to separation of interface and
implementation it increases the complexity of the
client program
It makes the code complex and difficult to
debug
40. Behavioral Patterns
Brent Ramerth
Abstract Factory, Builder
• The behavioral design patterns are design patterns that
identify common communication patterns between objects
and realize these patterns. By doing so, these patterns
increase flexibility in carrying out this communication.
• A behavioral pattern explains how objects interact
• It describes how different objects and classes and
messages to each other to make things happen and how
the various tasks are divided among different objects
41. 41
Behavioral Patterns
• Observer – The observer pattern is a pattern that defines
a link between objects so that when one object’s state
changes, all dependent objects are updated
automatically. This pattern allows communication
between objects in a loosely coupled manner.
• Strategy – It encapsulates an algorithm inside a class
• Command
• State
• Visitor
42. 42
Behavioral Patterns - Observer
Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated
automatically.
Intent
An abstraction has two aspects, one dependent on the other.
When changing one object requires changing others, and you don’t
know how many objects need changed.
When an object needs to notify others without knowledge about who
they are.
Applicability
43. 43
Observer
subject
observers
*
update()
ConcreteObserver
attach( observer )
detach( observer )
notify()
Subject
for all o in observers
o.update()
getState()
subjectState
ConcreteSubject
update()
<<interface>>
Observer
observerState :=
subject.getState()
Subject
Knows its observers, but not their “real” identity. Provides an interface for attaching/detaching observers.
Observer
Defines an updating interface for objects that should be identified of changes.
ConcreteSubject
Stores state of interest to ConcreteObserver objects. Sends update notice to observers upon state change.
ConcreteObserver
Maintains reference to ConcreteSubject (sometimes). Maintains state that must be consistent with
ConcreteSubject. Implements the Observer interface.
ConcreteSubject notifies observers when changes occur.
ConcreteObserver may query subject regarding state change.
Collaborations
Participants
44. 44
Behavioral Patterns - Observer
Subject
Knows its observers, but not their “real” identity.
Provides an interface for attaching/detaching observers.
Observer
Defines an updating interface for objects that should be identified of changes.
ConcreteSubject
Stores state of interest to ConcreteObserver objects.
Sends update notice to observers upon state change.
ConcreteObserver
Maintains reference to ConcreteSubject (sometimes).
Maintains state that must be consistent with ConcreteSubject.
Implements the Observer interface.
Participants
ConcreteSubject notifies observers when changes occur.
ConcreteObserver may query subject regarding state change.
Collaborations
46. Behavioral-Observer Pattern–Classification&
Applicability
A behavioral (object) pattern:
Concerns objects and their behavior.
Applicability
Vary and reuse 2 different abstractions
independently.
Change to one object requires change in
(one or more) other objects – whose
identity is not necessarily known
47. Behavioral-Observer Pattern –
Structure
Subject
attach (Observer)
detach (Observer)
Notify ()
Observer
Update()
Concrete Observer
Update()
observerState
Concrete Subject
GetState()
SetState()
subjectState
observers
subject
For all x in observers{
x.Update(); }
observerState=
subject.getState();
48. Strategy
There are common situations when classes differ
only in their behavior. For this case, is a good idea
to isolate the algorithms in separate classes in
order to have the ability to select different
algorithms at runtime.
This is a kind of design pattern in which a set of
similar algorithms to be defined and encapsulated
in their own classes
Thus this pattern is intended to define a family of
algorithms, encapsulate each of them and make
them interchangeable
Strategy is like Template Method
49. 49
Behavioral Patterns - Strategy
Pattern
Intent: Defines a family of algorithms, encapsulate each one, and
make them interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
Motivation: when there are many algorithms for solving a problem,
hard-wiring all algorithms in client’s code may have several
problems:
Clients get fat and harder to maintain
Different algorithms may be appropriate at different time
It is difficult to add new algorithms
51. 51
Behavioral Patterns - Participants of
Strategy
Strategy: declares an interface common to all supported
algorithm. Context uses this interface to call the algorithm
defined by a ConcreteStrategy.
ConcreteStrategy: implements the algorithm using the Strategy
interface
Context: maintains a reference to a Strategy object and defines
an interface that let Strategy access its data
52. 52
Behavioral Patterns - Sorting Example
Requirement: we want to sort a list of integers using different sorting
algorithms, e.g. quick sort, selection sort, insertion sort, etc.
E.g., {3, 5, 6, 2, 44, 67, 1, 344, ... }
{1, 2, 3, 5, 6, 44, 67, 344, ... }
One way to solve this problem is to write a function for each sorting
algorithm, e.g.
quicksort(int[] in, int[] res)
insertionsort(int[] in, int[] res)
mergesort(int[] in, int[] res)
A better way is to use the Strategy pattern
53. 53
Behavioral Patterns - Strategy Pattern
SortedList
SetSortStr(sortStr:SortStrategy)
Sort()
SortStrategy
Sort(list:ArrayList)
InsertionSort
Sort(list:ArrayList)
QuickSort
Sort(list:ArrayList)
MergeSort
Sort(list:ArrayList)
-sortStrategy
Main
Main()
stdRec
-list: ArrayList
Sort()
{sortStrategy.Sort(list)}
How is –sortStrategy implemented?
Main()
{…
stdRec.SetSortStr(sortStrInfo);
stdRec.Sort()}
How is stdRec implemente
54. Behavioral-Strategy
Define a family of algorithms, encapsulate
each one, and make them interchangeable.
Strategy lets the algorithm vary
independently from clients that use it.
54
_strategy.Algorithm();