Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 71

Design Patterns

CM0615 Week 11
Outline
Concepts

Basic Patterns

Advanced Patterns

Methodology
Concepts
Introduction

What is Design Pattern?

Principles

Documentation

Classification
Design Patterns : Intro
Same problems tend to recur, but designers
often solve them each time from first
principles.
Design Patterns attempt to describe generic,
successful solutions to recurring problems.
Originally applied in architecture: Christopher
Alexander.
Why re-invent the
wheel?
Its widely recognized that many (most?) design
problems commonly occur across different
domains or contexts.
Very few are totally unique. The same or similar
solutions are needed.
In reality, most designers do not indeed
approach each new problem from first principles.
They make use of proven solutions from past
problem domains, typically their own successful
designs but, if documented, the solutions from
other designers.
What is a Design Pattern?
A standard solution to a common problem
A design that has emerged through practical
experience with a number of projects and
development teams have found it to be
applicable in a variety of contexts.
Each design pattern describes a set of
communicating objects and classes. The set is
customized to solve a design problem in a
specific context.
A particular shape of object diagram, object
model, or module dependency diagram.
Parameterized
Collaboration
Within a model, we can represent a design
pattern as a parameterized collaboration in
the UML.
The design pattern is expressed in a general
way, with generic names for the collaborators.
Assigning domain-specific names makes the
pattern applicable to a specific model.
The parameterized collaboration helps you
visualize the specificity within the context of
the pattern.
Further Opportunities
OO designers are increasingly looking for
opportunities to reuse old solutions and to make their
successful designs available for reuse.
And its not just classes which can be reused:
opportunities for reuse have been extended to
coherent groups or frameworks of classes,
associations, properties and supporting code, i.e.
design patterns.
With design patterns (only a few years old) widely
accepted within the OO community, designers are
now looking at ANALYSIS and BUSINESS patterns to
support higher level reusability.
Three-part Rule
A pattern is a proven solution to a problem in a
context
Documenting patterns is one way that you can
reuse or share the information that youve learned
about how best to solve a specific design problem.
They codify the ways in which expert designers
tackle and solve particular commonly occurring
design problems.
Each pattern is a three-part rule which expresses a
relation between a certain context, a problem, and
a solution.
Example
Transaction-Transaction Line
T r a n s a c tio n T r a n s a c tio n L in e Transaction-Transaction Line
tr a n s a c tio n N o
tr a n s a c tio n D a te c o m p r is e s tr a n s L in e N o Item Pattern
tr a n s a c tio n V a lu e q u a n tity
1 * tr a n s L in e V a lu e Coad & Yourdon 1997
u p d a te T ra n s V a lu e ( )

Describing this P aym ent P a y m e n tL in e


p a y m e n tN o
structure as a p a y m e n tD a te c o m p r is e s p a y m e n tL in e N o
pattern p a y m e n tV a lu e
1 *
p a y m e n tL in e A m o u n t
p a y m e n tL in e V a lu e
highlights it as u p d a te P a y m e n tV a lu e ( )
useful
experience
readily available
to the novice.
Key Principles
Key principles that underlie patterns
Abstraction
Modularization
Completeness and primitiveness
Separation of policy and implementation
Single point of reference
Divide and conquer
Buschmann et al. (1996)
Documentation Principles
Whilst Gamma et al. (who first recognized the value
of design patterns to OO development) provide a
catalogue of off-the-peg (ready-made) design
patterns, ready for use, the expectation is that
designers will extend such a catalogue with their
own proven patterns.
To support pattern development, basic principles for
documenting design patterns have been agreed.
Every pattern should express the PROBLEM
solved, the context in which to be applied and
details of the SOLUTION and CONSEQUENCES.
Classification
Creational Patterns
Concern themselves with the process of object creation
Structural Patterns
Deal with the composition of objects and classes
Behavioural Patterns
Specify how classes or objects interact and allocated
responsibility
Scalability Patterns
Deal with the access to similar data from multiple clients

Scope
In terms of whether they apply to objects or classes
Basic Patterns
Singleton

Factory

Composite

State
Creational Patterns
Concerned with the construction of object
instances.
Decoupling the operation of an application
from how its objects are created. Gives
designer more flexibility in configuring these
objects.
Analogy: staff holidays in a companys
systems development department may
require short-term cover from contractors.
Examples
Singleton
Creating classes which must have only a single
instance
Factory
Used when a class cannot anticipate the class
of objects it must create
Abstract Factory
Provides an interface for creating families of
related objects
Singleton Pattern
The Singleton design pattern (proposed by Gamma et
al) is perhaps the most straightforward, involving, as
it does, only one object.
It applies to the many situations where there must
only be a single instance of a class (e.g. the
application object offering a single interface between
hardware and application).
Responsibility for ensuring that only one instance can
ever be created cannot safely be left with the
programmer too many loopholes. Better solution is
to make the class itself responsible for keeping track
of its instances.
The Singleton Pattern
Name: Singleton
Problem: In some applications it is important that a class
have exactly one instance. How can a class be constructed
that should have only one instance and that can be
accessed globally within the application?
Solution: Create a class with a class/static method
getInstance(). The constructor must be private.
Consequences:
Control access to sole instance encapsulate its sole instance
Reduced name space avoids polluting the name space with
global variables
Permits refinement of operations and representation might
be sub-classed
Example - Singleton
Pattern
Context:
A sales order processing application
may be dealing with sales for one
company. It is necessary to have a
company object that holds details of
the companys name , address, C om pany
reference number and so on. Clearly c la s s - s c o p e ( s ta tic )
c o m p a n y In s ta n c e
there should only be one such a ttr ib u te
com panyN am e
object. c o m p a n y A d d re s s
Solution: c la s s - s c o p e ( s ta tic )
g e tC o m p a n y In s ta n c e ()
o p e r a tio n
When the class is first accessed, g e tC o m p a n y D e ta ils ( )
creates the relevant object instance
and returns the object identity to
the client.
Access doesnt require global
definition of object-id (violating
encapsulation). Class (static)
operation getCompanyInstance()
provides any client object with the
id for the Company instance.
The Factory Pattern
Name: Factory

Problem: Concerned with the encapsulation of object


creation details

Solution
Typically has a method for every kind of object it is capable
of creating.

Consequences
Instantiating an object with complex configuration etc.
Reuse without significantly duplicating code
Access of information not within the composing object
Centralised lifetime management for consistent behaviour
Factory Design Pattern
Used to encapsulate the processes involved in
the creation of objects. It is an abstraction of a
constructor, and can be used to implement
various allocation schemes, such as the
singleton pattern.
Typically has a method for every kind of
object it is capable of creating. These methods
optionally accept parameters defining how the
object is created, and then return the created
object.
Factory Design Pattern
When to use:
Instantiating an object of a particular kind is a more
complex process than simply creating a new object such
as to create the object's class (if applicable) dynamically,
return it from an object pool, do complex configuration
on the object etc..
The creation of the object precludes reuse without
significantly duplicating code
The creation of the object requires the access of
information or resources not appropriate to contain
within the composing object
The lifetime management of created objects needs to be
centralised to ensure consistent behaviour
Factory Design Pattern (Agate Case
Study)
sd Get company name for display

:RequestingObject Company

alt [companyInstance == null]

getCompanyInstance
Company singleInstance
:Company
companyInstance =
companyInstance = Company
getCompanyInstance

[else]
getCompanyInstance

companyInstance =
getCompanyInstance

getCompanyName

displayName = getCompanyName
Factory Design Pattern (Agate Case
Study)
Company
- companyInstance
The operation - companyName
getCompanyDetails() - companyAddress The attribute
has been moved to the + getCompanyInstance() companyRegistrationNumber
subclasses where it is + getCompanyDetails() has been moved to the
polymorphically redefined - Company() subclasses where it is defined
in each. differently in each.

UKCompany USACompany FrenchCompany

- companyRegistrationNumber - companyRegistrationNumber - companyRegistrationNumber

+ getCompanyDetails():String + getCompanyDetails():String + getCompanyDetails():String


- UkCompany():UkCompany - USACompany():USACompany - FrenchCompany():FrenchCompany

Different subclasses of Company can be instantiated


as needed, depending on run-time circumstances
Structural Patterns
Concerned with the way classes and objects
are organised.
Offer effective ways of using inheritance,
aggregation and composition to satisfy
particular requirements.
may be a requirement to minimise the impact
of future change or extension.
may be a requirement to design an interface
which can manage interaction between several
different classes.
The Composite Pattern
Name: Composite
Problem: There is a requirement to represent
whole-part hierarchies so that both whole and part
objects offer the same interface to client objects.
Context: In an application both composite and
component objects exist that are required to offer
the same behaviour. Client objects should be able
to treat composite or component objects in the
same way.
Solution: Combine inheritance and aggregation
hierarchies.
Composite
Com ponent c h ild r e n
C lie n t *
o p e r a tio n ( )

Leaf C o m p o s ite
o p e r a tio n ( ) o p e r a tio n ( )

fo r a ll g in c h ild r e n
g - > o p e r a tio n ( )

Compose objects into tree structures, letting clients treat


individual objects and compositions of objects uniformly.
Like many design patterns, its built around an abstract class.
Part-whole Hierarchies
The Composite pattern expresses a recursive
structure for part-whole hierarchies.
An abstract class (Component) offers a
consistent interface through which clients can
access and manipulate the composite
structures.
Access is gained by calling the operation()
virtual member function, which must be
defined explicitly in each of the concrete
subclasses.
Leaf/Composite
A concrete component can either be:
a Leaf, which has no subcomponents of its
own, or
a Composite, which can have any number of
subcomponents.
The Operate() function in the Composite
concrete subclass would trigger the operation
function of each of its children, as shown by
the annotation.
Composite : Example
E le m e n t
c o m p o n e n ts
D r a w in g 1 * d ra w () *
m o v e ()

R e c ta n g le L in e E llip s e G ro u p

d ra w () d ra w () d ra w () d ra w ()

f o r a ll c in c o m p o n e n t s
c -> d ra w ()

Class diagram for a Diagram Editor


A Drawing will have several elements, each of which may be one of the defined shapes.
Element delegates draw() to each of its component sub-classes, where the operation is
polymorphically redefined.
Behavioral Patterns
Concerned with the way responsibilities are
assigned to classes and how algorithms are
designed.
Describe particular static relationships between
objects and classes and how the objects
communicate.
Behavioral patterns make strong use of
inheritance hierarchies (to share out
responsibilities) and
aggregation associations (to model complex
interactions) .
The State Pattern
Name: State
Problem: An object exhibits different behaviour
when its internal state changes making the object
appear to change class at run-time.
Context: In some applications an object may have
complex behaviour that is dependent upon its
state.
Solution: The state pattern separates the state
dependent behaviour from the original object and
allocates this behaviour to a series of other
objects, one for each state.
State
C o n te x t S ta te

o p e r a tio n ( ) o p e r a tio n ( )

C o n c re te S ta te A C o n c r e te S ta te B
o p e r a tio n ( ) o p e r a tio n ( )

An object exhibits different behaviour when its internal state changes making the object appear to
change class at run-time.
State pattern separates state dependent behaviour from the original object and allocates this
behaviour to a series of other objects, one for each state.
Responsibility for the objects behaviour delegated to the appropriate state object.
When?
To determine whether it has features that may
justify the application of the state pattern.
First, are there any objects with significant state
dependent behaviors?
Second, the state dependent operations would
normally need to be specified with a series of
case or if-then-else statements to test the state
of the object.
Advanced Patterns
Decorator

The Faade Pattern

Model-View-Controller (MVC)

Asynchronous Page

Caching Filter

Resource Pool
The Decorator Pattern
Problem: Dynamically add functionality to a
single, central component to perform common
functionality.
Solution
Participants
Component a common interface implemented by both decorators
and the target
Decorators Encapsulate a piece of common functionality, such as
decryption or logging, while presenting the same interface as the
target
Target the final object in the request processing chain, coordinates
all specific activities such as input handling.
Interaction
The Decorator intercepts all requests destined for the target and
performs a common function such as logging or decryption. Then
forwards the request to the next decorator in the chain, or the target
if there are no more decorators.
Decorator Pattern
Combines multiple small components into a single
piece
A wrapper: a class that contains a single child and
presents the same interface as that child.
Decorates, or adds a piece of functionality to its
child.
When a method is called on the decorator it does its
own processing and then calls the corresponding
method on the child. The result is an extended
response. Code that relies on the child doesnt need
to know that it is using the decorator instead of the
child.
Decorator Pattern
Could be chained (multiple levels of
decorators): a chain consists of multiple
decorators, each decorating the original
object at the end of the chain. It calls the
methods of the next object in the chain.
Chains might have an arbitrary length
Only decorates a single component to allow a
chain of arbitrary length
Add/remove dynamically decorators
Decorators have to be independent from each
other and the target to allow dynamic chain
Decorator Pattern
(interactions)
Decorator Pattern
(continued)
Implementation
This wrapping could be achieved by the
following sequence of steps:
1. Subclass the original "Component" class
into a "Decorator" class;
2. Decorator class defines an interface that
conforms to Component's interface;
3. Maintains a reference to a Component
add a Component pointer as an attribute
and pass a Component to the Decorator
constructor to initialize the Component
pointer;
4. In the Decorator class, redirect all + operation()
+decoratorFunction
"Component" methods to the ()

"Component" pointer;
5. In the ConcreteDecorator class, add
responsibilities to the component
Extra
decoratorFunction().
The Faade Pattern
Problem: Who should be responsible for handling a
system operation message from an actor?
Solution: Assign this responsibility to an object
representing the system as a whole.
Consequences:
Simple interface to a complex subsystem
There are many dependencies between clients and the
implementation classes of an abstraction. Introduce a
faade to decouple subsystem from clients and other
subsystems promoting system independence and
portability
To layer the subsystems
The Faade Pattern (continued)
Model-View-Controller (MVC)
Presentation tier
Model application state
View interprets data in the model and
presents it to the user/client
Controller processes the user/client input and
either updates the model or displays a new
view
Model-View-Controller (MVC)
(classes)
Model-View-Controller
(Interactions)
Controller receives the input and translates it
into appropriate updates to the model.
The model applies the business rules and
stores the data persistently, either locally in
the business tier or remotely.
Based on the model changes and user input
the controller chooses a view.
The view transforms the updated model into a
form suitable for the user/client.
Model-View-Controller
(Interactions)
Model-View-Controller
(Interactions)
Presentation Tier
Scalability
In an enterprise applications many clients need to
access similar data. The server may respond to
hundreds of requests per minute for the same material.
It uses a backend database to store the information. It
would be inefficient for the system to contact the db
for each request.
Some speed can be sacrificed up front for better
performance in the average case. While the first
request for a connection to a particular database might
require a lot of work, subsequent requests will be much
faster. Scalability increases because more requests
can be supported in the same amount of time.
Scalability Approaches
Asynchronous Page
How to cache data and use it to generate
dynamic pages
Caching Filter
Can be used to cache entire dynamic pages
after they are generated
Resource Pool
How to create a pool of large or expensive
objects that can be loaned out as needed,
saving instantiation cost.
Content Caching
Caching static web pages is well established
practice on the web on routers, switches as
standard infrastructure components.
A Web cache maintains copies of the most
frequently required files, which allows it to serve
those requests quickly without involving the real
web server.
Approaches:
Caching the input used to generate dynamic content
Caching the generated content
Asynchronous Page
Takes advantage of asynchronous retrieval of
remote resources to improve scalability and
performance.
Rather then waiting for a request a server
(subscriber) may accept the data as
generated by the publisher.
When a request comes for particular data the
server replies with the data already received.
Asynchronous Page
Pattern
Name: Asynchronous Page
Problem: Cache remote data as generated
Solution
Participants:
Publisher remote entities that generate new data at some interval. May
also notify subscribers when new data is available
Subscriber A singleton object responsible for retrieving, formatting, and
caching remote data either as it generated or at some interval
Models Store data for applications
Views When requests are received, translate model data into a format
appropriate for display to the user
Interactions: The subscriber retrieves data from the publisher either when
it has changed or at some predefined interval. The subscriber process the
data and updates all appropriate models. When requests are received, the
view translates current model data into format suitable for the user.
Asynchronous Page
Caching Filter
Uses a filter (see the Decorator pattern about filters) to
cache dynamically generated pages.
It is a specific implementation of a Decorator. It represents
API to its only child and also provides extra methods to
read pages from cache as well to add the results of
existing a particular request to the cache. When a request
comes in, the cached page is simply returned if it is in the
cache. Alternatively the rest of the chain must be executed
and the result put in the cache.
The caching filter could be added anywhere in the chain,
caching the results from all the filters after.
When applied to the presentation tier it caches fully
generated dynamic pages.
Caching Filter Pattern
Problem: Minimize repeated page generation by
caching dynamic pages when they are generated
Solution
Participants:
Filter A common interface implemented by the cache,
decorators and target
Cache filter Intercepts all requests and replies

efficiently with cached pages if available. Alternatively


caches the results of generating the page
Decorators Encapsulate a piece of common

functionality, while presenting the same interface to the


target
Caching Filter Pattern
Solution
Target The final object in the request
processing chain. Coordinates all specific
activities, such as input handling. Typically the
front controller
Interactions:
The cache filter intercepts all requests destined for
target and determines if the page has been cached.
If cached it is returned from the cache alternatively
the remaining decorators in the chain and the target
are executed to generate the page, and the results
are cached.
Caching Filter
(structure)
Caching Filter (interactions)
Sharing Resources
At the extreme an entire application with a
single db connection for example shared
between all clients.
Obviously, sharing resources is a must for
scalability but it has costs too.
While this effectively removes the cost of creation
it limit parallelism since the access to the resource
(such as db) has to be synchronized in some way.
Sharing connections also prevents individual
components of the application to from engaging in
transactions.
Resource Pool
If the connections are not shared the connections
and costs grow with the number of requests. As the
costs add up limits the number of clients that an
application can support.
A resource pool is a collection of procreated objects
that can be loaned out to save the expense of
creating them many times.
When a distributed/networked connection/request
comes in, a thread is retrieved from the thread pool to
handle the request.
If it requires access to a database the connection will
come from a connection pool.
Resource Pool
(continued)
Pools are prevalent because they solve two scalability
problems simultaneously:
Share the cost of instantiating and maintenance complex
resources over multiple instances.
Create a single point for effective tuning and fine-grained
control of the system resources allowing precise
regulation of parallelism and memory use at run time by
changing the pool parameters. The number of the pool
resources (such as connections) has an upward boundary,
so dont spiral out of control.
Putting more objects in the pool uses more memory
and increases start-up time, but usually means that it
can support more clients.
Resource Pool
(continued)
Amortizes the start-up costs over multiple
objects and allowing fine-grained control of
the system resources such as memory and
CPU usage.
Responsible for creating, maintaining, and
controlling access to the resource objects.
The contents and use of a resource must be
coordinated between the creator of the pool
and the various clients.
Usually pools only store one type of objects.
Resource Pool Pattern
A client calls the getResource() method to get an instance of the
resource.
Advanced implementations even allow a filter to be provided to the
getResource() method in order to specify desired criteria of the
resource.
When it is finished, it uses the returnResource() method to add
the resource back to the pool.
The pool uses a Factory object to create the actual resources.
The factorys createResource() method is used to generate a new
instance of a resource.
Before a resource is used, the pool calls the factorys
validateResource() method to reset the resource to its initial state.
For further efficiency, the factory may even try to repair the returned
object such as reopening db connection. This is called recycler
method.
Resource Pool Pattern
Problem: Decrease costs of instantiating and maintaining large
objects using a pool of pre-generated objects
Solution
Participants
Pool A limited collection of pre-generated objects that can be loaned out
and returned.
Factory Used by the pool to generate new instances of a resource or

validate a returned resource


Resource An object that will be loaned out by the pool.

Interactions
The client requests objects from the pool, which returns a resource if one
is available. If not, but the pool is not at capacity, a new instance is
generated using the factory. If all resources are loaned out, the client waits
until one becomes available. When the client has finished using the
resource, it returns it to the pool, which uses the factory to validate the
returned resource.
Resource Pool Pattern (structure)
Resource Pool Pattern
(Interactions)
Methodology
Selecting a Design Pattern

Using a Design Pattern


Selecting a Design
Pattern
Be sure you understand how design patterns
can solve design problems.
Study how patterns interrelate
Consider what should be different in your
design
Simpler solution
More acceptable alternative
Patterns context consistent with the problem
Consequences acceptable
Using a Design Pattern
Read the pattern once through for an
overview.
Go back and study the detailed sections.
Look at the sample code to see a concrete
example of the pattern in code.
Define the classes.
Define application-specific names for
operations.
Implement the operation to carry out the
responsibilities.
Reading
Closely read Bennett Chapter 15
Simon Bennett, Steve McRobb, Ray Farmer (2006) Object-
oriented systems analysis and design using UML, McGraw-Hill
Higher Education
Larman, Craig (2005) Applying UML and patterns : an
introduction to object-oriented analysis and design and
iterative development, Prentice Hall
Shalloway, Alan (2002) Design patterns explained : a new
perspective on object-oriented design, Addison-Wesley
Erich Gamma, Richard Helm, Raph Johnson, and John Vlissides
(1995) Design Patterns: elements of reusable object-oriented
software , Addison-Wesley
William Crawford & Jonathan Kaplan (2003) J2EE Design
Patterns, OReilly

You might also like