You are on page 1of 285

Design Patterns Introduction

Design Principle
 “One cannot design a solution, if requirement is not clear”
 “One cannot implement the design, if design is faulty”
 Aim of Design Principle is to achieve the desirable goal of
a good design”
 Functional Requirement: may involves calculation,
technical details, data manipulation & processing & other
specific functionality that define what a system is supposed
to accomplish.
 Non-Functional Requirement: Scalability, Serviceability,
availability, reliability, recoverability, maintainability.
Why OO?
 Software crisis – Communication difficulties
and the management of complexity.
 The communication and complexity about the
problem and the solution, all are expressed in
terms of the concept language.
Concepts and Objects
When given a list of concepts (water, salt water,
Oceans, Penguins,...),
Harry constructed a concept diagram through
which he understands his world and
communicates meaning
… for Conceptual … Modeling Reasons
 What kind of language can be used to create
this concept diagram, or Harry’s mental
image?

Water
Fresh water
have

Rivers Oceans have


have live in Salt water
have
Crocodiles
Fish have

Penguins
Why OO?
 To understand why a software system is
needed, what it should do, and how it should
do it (by taking example of SRS).
 To communicate our understanding of why,
what and how.
 To detect commonalities and differences in
your perception (observation), my perception,
his perception and her perception of reality.
 To detect misunderstandings and
miscommunications.
Modeling
 It consists of building an abstraction of
reality.
 Abstraction are simplification, because
 They ignore irrelevant details &
 They only represent the relevant details
 What is irrelevant & relevant depends on
purpose of the model.
Why Modeling Need in Software Development
 During software development, it getting
increasingly more complex.
 “A single programmer can’nt manage the
amount of code in its entirely”
 Code is not easily understandable by developers
who did not write it.
 We need a simpler representation for the
complex system.
 Modeling is a mean for dealing with complexity.
Analysis
 Investigate the problem and the requirement.
 What is needed?
 Required Function?
 Investigate the Domain Object
 The whats of the system
 Do the right thing
Design
 Conceptual solution that meets the
requirements.
 No an implementation.
 Describe a data schema and software objects.
 Do the things right (design).
What is OOAD?
 Analysis — understanding, finding and describing
concepts in the problem domain.
 Design — understanding and defining software
solution/objects that represent the analysis concepts
and will eventually be implemented in code.
 OOAD — Analysis is object-oriented and design is
object-oriented. A software development approach
that emphasizes a logical solution based on object.
How to Do OOAD
Software Lifecycle

Systems Engineering

Requirements Analysis

Quality Assurance
Project Planning
Maintenance
Architectural Design

Detailed Design

Implementation
Something missing?

Release

What’s yours like?


OMT (Object Modeling Technique) by James Rumbaugh

Object Model: describes the static


structure of the objects in the system and
their relationships -> Object Diagrams.

Dynamic Model: describes the


interactions among objects in the system
-> State Diagrams.

Functional Model: describes the data


transformation of the system
-> DataFlow Diagrams.
Analysis:
i) Model the real world showing its important
properties;
ii) Concise model of what the system will do

System Design:
Organize into subsystems based on analysis
structure and propose architecture

Object Design: Based on analysis


model but with implementation details;
Focus on data structures and
algorithms to implement each class;
Computer and domain objects

Implementation: Translate the object


classes and relationships into a
programming language
OOPL
 Object: anything to which concept applies.
 Abstraction: Focus on essential, omits irrelevant
details.
 Encapsulation: Information Hiding
 Class: collection of objects that share common
properties, attributes, behaviour and semantics.
 Classification: grouping of common objects into a
class.
 Specialization: acts of defining one class as a
refinement of another.
OOPL
 Subclass
 Superclass
 Inheritance
 Polymorphism: objects of different classes
responds the same message differently.
How to Do OOAD
- Historical Perspective

OO Technology Process Perspective

OO Prog. Languages just program!


(Smalltalk, C++)

OO Design
(Booch) design then
program

OO Analysis Analyze (use case) first,


(Rumbaugh, Jacobson) then design,
T then program

Where are we heading?


1. How do you think your mental image is represented?
2. What kinds of languages are used for what purpose in our daily
life?
3. What are the differences among a concept, a model and a language?
4. What are the differences between a language and a methodology?
5. Can we use C# for analysis?
6. If C++ is a language, does it model anything? If so, what?
7. What does a concept in C++ refer to (i.e., semantics)?
8. What does a concept in a (OO) design refer to?
9. What does a concept in an (OO requirements) analysis refer to?
10. Is the current OOAD for Functional Analysis and Design, or Non-
Functional Analysis and Design?
11. What is the relationship between OO (Object-Orientation) and GO
(Goal-Orientation), between OO and AO (Agent-Orientation), and
between GO and AO?
12. Can you prove you and I communicate with each other perfectly?
What is a Design Pattern?
 A (Problem, Solution) pair.

 A technique to repeat designer success.

 Borrowed from Civil and Electrical


Engineering domains.
Design Pattern
 Design Pattern are the solution to general problems that
software developer faced during Software Development.
 It is introduced in software development – 1994
 It is the way through which – grouping of classes with
specific responsibility or interfaces.
 Design pattern are solution for common design
problems, that use design principle to achieve these
desirable goals of a good design.
 It provides, reusable solution to a common design
problem.
Design Pattern
 According to design pattern, the principles of OOD
 The program to an interface not an implementation
 Favour object composition over inheritance
 A Design pattern provides, reusable solution to a
common design problem.
 It provides specific solution to specific problem
 Is the way through which – grouping of classes
with specific responsibilities or interfaces
Usage of Design Pattern
 Design Patterns have two main usages in software development.
 Common platform for developers
 Design patterns provide a standard terminology and are specific
to particular scenario. For example, a singleton design pattern
signifies use of single object so all developers familiar with
single design pattern will make use of single object and they
can tell each other that program is following a singleton pattern.
 Best Practices
 Design patterns have been evolved over a long period of time
and they provide best solutions to certain problems faced during
software development.
 Learning these patterns helps unexperienced developers to learn
software design in an easy and faster way.
Design Pattern
 Design pattern become an essential part of OOD and
OOP.
 They provides elegant and maintainable solutions to
commonly encountered programming problem.
 A design pattern provides description of a design solution,
that can be adapted and applied to a specific situation.
 The GOF(Gang of Four) design pattern provides 23
different types of design pattern that are arranged in 3
classes.
 The group helps classify, how the patterns are used.
Types of Design Patterns
 There are more then 23 design patterns which can be
classified in three categories: Creational, Structural and
Behavioral patterns.
 Creational Patterns
 These design patterns provide a way to create objects while
hiding the creation logic, rather than instantiating objects
directly using new operator.
 This gives program more flexibility in deciding which
objects need to be created for a given use case.
 Are used to help make a system independent of how the
objetcs it uses are created,
 Structural Patterns
 These design patterns concern class and object
composition.
 Concept of inheritance is used to compose
interfaces and define ways to compose objects to
obtain new functionalities.
 It concerned with how classes and object are
organised and composed to build larger structures.
Behavioral Patterns
 These design patterns are specifically concerned
with communication between objects.
 Behavioural pattern are used to deal with
assignment of responsibility of object and
communication between the objects.
 J2EE Patterns
These design patterns are specifically concerned with
the presentation tier.
 These patterns are identified by Sun Java Center.
 Factory pattern is one of the most used design patterns
in Java. This type of design pattern comes under
creational pattern as this pattern provides one of the best
ways to create an object.
 In Factory pattern, we create object without exposing the
creation logic to the client and refer to newly created
object using a common interface.
Designer How Patterns are used?
 Design Problem.
Programmer
 Solution.
 Implementation details.

Reduce gap

Design Implementation

Gamma, E., Helm, R., Johnson, R., Vlissides, J.: Design patterns: elements of reusable
object-oriented software. 1995.

Buschmann, F., Meunier, R., Rohnert, H., Sommerlad, P., Stal, M.: Pattern-oriented
software architecture: a system of patterns. 2002.
Design patterns you have already seen
 Encapsulation (Data Hiding)
 Subclassing (Inheritance)
 Iteration
 Exceptions
Encapsulation pattern
 Problem: Exposed fields are directly
manipulated from outside, leading to
undesirable dependences that prevent
changing the implementation.

 Solution: Hide some components, permitting


only stylized access to the object.
Exception pattern
 Problem: Code is cluttered (jumbled) with
error-handling code.

 Solution: Errors occurring in one part of the


code should often be handled elsewhere.
 Use language structures for throwing and
catching exceptions.
Derived Conclusion
 Patterns are Programming language features.

 Programming languages are moving towards


Design.

 Many patterns are being implemented in


programming languages.
Pattern Categories
 Creational Patterns concern the process of
object creation.

 Structural Patterns concern with integration


and composition of classes and objects.

 Behavioral Patterns concern with class or


object communication.
What is the addressing Quality
Attribute?
 Modifiability, Exchangeability, Reusability, Extensibility,
Maintainability.

What properties these patterns provide?


 More general code for better Reusability.

 Redundant code elimination for better


Maintainability.
Designer How Patterns are used?
 Design Problem.
Programmer
 Solution.
 Implementation details.

Reduce gap

Design Implementation

Gamma, E., Helm, R., Johnson, R., Vlissides, J.: Design patterns: elements of reusable
object-oriented software. 1995.

Buschmann, F., Meunier, R., Rohnert, H., Sommerlad, P., Stal, M.: Pattern-oriented
software architecture: a system of patterns. 2002.
Creational pattern.
 These design patterns provide a way to create
objects while hiding the creation logic, rather than
instantiating objects directly using new operator.
 This gives program more flexibility in deciding
which objects need to be created for a given use
case.
 Are used to help make a system independent of
how the objetcs it uses are created,
Factory Pattern
 Factory Pattern is one of the most used design patterns in
JAVA.
 This type of design pattern comes under Creational
pattern.
 And it provides one of the best ways to create an object.
 In it, we create object without exposing the creation Logic
to the client and refer to newly object using a common
interface.
 We're going to create a Shape interface and concrete
classes implementing the Shape interface. A factory
class ShapeFactory is defined as a next step.
Implementation
 FactoryPatternDemo, our demo class will
use ShapeFactory to get a Shapeobject. It will pass
information (CIRCLE / RECTANGLE / SQUARE)
to ShapeFactory to get the type of object it needs.
Problem
 A framework needs to standardize the
architectural model for a range of applications,
but allow for individual applications to define
their own domain objects and provide for their
instantiation.
Abstract Factory
 Abstract Factory patterns work around a super-
factory which creates other factories.
 This factory is also called as factory of factories.
 This type of design pattern comes under
creational pattern as this pattern provides one of
the best ways to create an object.
 In Abstract Factory pattern an interface is
responsible for creating a factory of related
objects without explicitly specifying their classes.
 Each generated factory can give the objects as per
the Factory pattern.
 The Client deals, AbstractFactory, AbstractProductA and Abst
ractProductB. It doesn't know anything about the
implementations.
 The actual implementation of AbstractFactory that
the Client uses is determined at runtime.
 As you can see, one of the main benefits of this pattern is that the
client is totally decoupled from the concrete products.
 Also, new product families can be easily added into the system, by
just adding in a new type of ConcreteFactory that
implements AbstractFactory, and creating the specific Product
implementations.
For completeness, let's model the Clients interactions in
a sequence diagram:
Purpose of the Abstract Factory
 The purpose of the Abstract Factory is to
provide an interface for creating families of
related objects, without specifying concrete
classes
Singleton Pattern
 It is one of the simplest design pattern in Java
 It is a type of Creational Design Patterns
 This type of design pattern basically used in application
domain:
 When you need to have only one instance of an object
at any time.
 Singleton pattern ensures that there is only ever one
single instance of a class, it prevents any others object
from being instantiated from that class.
 Online booking reservation  website
.
 This pattern involves a single class which is
responsible to create an object while making sure
that only single object gets created.
 This class provides a way to access its only object
which can be accessed directly without need of
instantiate the object of class.
Singleton Pattern
 Sharing a single washing machine among all
the residents in a hotel or sharing a single
appliance like refrigerator among all the
family members.
 Every Java application has a single instance
of class Runtime that allows the application to
interface with the environment in which the
application is running.
Builder Pattern
 Builder pattern builds a complex object using
simple objects and using a step by step
approach.
 This type of design pattern comes under
creational pattern as this pattern provides one
of the best ways to create an object.
 A Builder class builds the final object step by
step.
 This builder is independent of other objects.
Builder Pattern
 For Example
 We have considered a business case of fast-
food restaurant where a typical meal could be
a burger and a cold drink.
 Burger could be either a Veg Burger or
Chicken Burger and will be packed by a
wrapper.
 Cold drink could be either a coke or pepsi and
will be packed in a bottle.
Prototype pattern
 Prototype pattern refers to creating duplicate object
while keeping performance in mind.
 This type of design pattern comes under creational
pattern as this pattern provides one of the best ways to
create an object.
 This pattern involves implementing a prototype
interface which tells to create a clone of the current
object.
 This pattern is used when creation of object directly is
costly.
 So this pattern works by cloning of an object rather
than creation unlike Factory patterns.
When to use this pattern?
 If the cost of creating the object is expensive or
complicated.
 When trying to keep the number of classes in an
application to a minimum
 When adding or removing objects at runtime
 When the client application needs to be unaware
of the object creation, composition and
representation.
 Objects are required which are similar to the
existing objects
For example
 an object is to be created after a costly database
operation.
 We can cache the object, returns its clone on
next request and update the database as and
when needed thus reducing database calls.
 Prototype pattern refers to creating duplicate
object while keeping performance in mind.
This type of design pattern comes under
creational pattern as this pattern provides one
of the best ways to create an object
 .
Structural Pattern
 These design patterns concern class and
object composition.
 Concept of inheritance is used to compose
interfaces and define ways to compose objects
to obtain new functionalities.
 It concerned with how classes and object are
organised and composed to build larger
structures.
Adapter pattern
 Adapter pattern works as a bridge between two incompatible interfaces.
 This type of design pattern comes under structural pattern as this pattern combines the capability of two
independent interfaces.
 This pattern involves a single class which is responsible to join functionalities of independent or
incompatible interfaces.
 A real life example could be a case of card reader which acts as an adapter between memory card and a
laptop.
 You plugin the memory card into card reader and card reader into the laptop so that memory card can be
read via laptop.
 It is used to identifying a simple way to realize
relationship between entities.
 Combine the capabilities of two independent interface.
 The best example for the adapter pattern is based around
AC power adapters.
 Say you're visiting Europe from the US, with your
laptop, which expects a US power supply.
 To get your laptop plugged in, you're going to need to
get a power adapter that accepts your US plug and
allows it to plug in to the European power outlet.
 The AC adapter knows how to deal with both sides,
acting as a middleman - this is the adapter pattern.
For example
 We have a MediaPlayer interface and a concrete class 
AudioPlayerimplementing the MediaPlayer interface. AudioPlayer can
play mp3 format audio files by default.
 We are having another interface AdvancedMediaPlayer and concrete
classes implementing the AdvancedMediaPlayer interface. These classes
can play vlc and mp4 format files.
 We want to make AudioPlayer to play other formats as well. To attain
this, we have created an adapter class MediaAdapter which implements
the MediaPlayer interface and uses AdvancedMediaPlayer objects to play
the required format.
 AudioPlayer uses the adapter class MediaAdapter passing it the desired
audio type without knowing the actual class which can play the desired
format. AdapterPatternDemo, our demo class will use AudioPlayer class
to play various formats.
Adapter pattern
 The Adapter is known as a structural pattern,
as it's used to identifying a simple way to
realize relationships between entities
Adapter Design Pattern Example
 Lloyds bank is an international bank offers services
worldwide.
 For offshore account holders, the tax rate is 0.03%.
 And, in India it offers two types of accounts,
Standard and Platinum.
 Tax rules are not applied to indian bank accounts.
 Now the offshore bank is incompatible to Indian
account types.
 We need to design an AccountAdapter to make both
the incompatible account types to work together.
Bridge Pattern
 Bridge is used when we need to decouple an abstraction
from its implementation so that the two can vary
independently.
 This type of design pattern comes under structural pattern
as this pattern decouples implementation class and abstract
class by providing a bridge structure between them.
 This pattern involves an interface which acts as a bridge
which makes the functionality of concrete classes
independent from interface implementer classes.
 Both types of classes can be altered structurally without
affecting each other.
For example
 We are demonstrating use of Bridge pattern
via following example in which a circle can
be drawn in different colors using same
abstract class method but different bridge
implementer classes.
 For example :
 Security System
 Security System is a security and electronic company
which produces and assembles products for cars.
 It delivers any car electronic or security system you
want, from air bags to GPS tracking system, reverse
parking system etc.
 Big car companies use its products in their cars.
 The company uses a well defined object oriented
approach to keep track of their products using software
which is developed and maintained by them only.
 They get the car, produce the system for it and
assemble it into the car.
Bridge Pattern
 Suppose there is a company that manufactures
various types of vehicles, like bikes, cars, and
buses.
 There are frequent changes in the vehicle, as
new models of bikes and cars can be
introduced and have different processes to
manufacture them.
Filter pattern or Criteria pattern
 It is a design pattern that enables developers to
filter a set of objects using different criteria and
chaining them in a decoupled way through
logical operations.
 This type of design pattern comes under
structural pattern as this pattern combines
multiple criteria to obtain single criteria.
 Filter design pattern is used for building a criteria
to filter items or objects dynamically.
 You can choose your own criteria and apply it on
your objects to filter out the desired objects.
 You are building a tool to help tech-ops team in your
company to distribute laptops to employees according to
their configuration requirements.
 Each role in company has a different configuration
requirement.
 Now tech-ops team have a very hard time to filter out the
laptops as per the employee requirement because its a
manual process.
 The tool you are building provides a functionality to the
employees to add filters to search for their desired laptop.
 The filters may change across the employees.
Filter pattern or Criteria pattern
 Filter pattern or Criteria pattern is a design
pattern that enables developers to filter a set
of objects using different criteria and chaining
them in a decoupled way through logical
operations.
Composite pattern
 The composite design pattern allows us to create
composite objects from different components.
 Composite pattern composes objects in term of a tree
structure to represent part as well as whole hierarchy.
 This type of design pattern comes under structural
pattern as this pattern creates a tree structure of group
of objects.
 This pattern creates a class that contains group of its
own objects.
 This class provides ways to modify its group of same
objects.
 We will use an information system for managing
student records.
 Students can do all or part of the following activities
in a typical college / university.
 New students fill in application forms
 Students enroll for semester courses
 Students subscribe for services such as internet usage,
library etc.
 Students register for exams
 Students occasionally break school property
 The above activities give us a structured hierarchy
of students’ activities that are different in nature
When should I use composite design pattern?
 A Composite is a pattern that is useful anytime you may
need to selectively treat a group of objects that are part of
a hierarchy as "the same" when they are in fact different.
 Typically the examples used talk in terms of treating
leaves and nodes the same, but the pattern can also be
extended to heterogeneous lists.
 This pattern should be used when you want to represent
objects in a hierachical fashion, or you need objects and
composites to be treated uniformly. 
Decorator pattern
 Decorator pattern allows a user to add new functionality
to an existing object without altering its structure.
 This type of design pattern comes under structural pattern
as this pattern acts as a wrapper to existing class.
 This pattern creates a decorator class which wraps the
original class and provides additional functionality
keeping class methods signature intact.
 We are demonstrating the use of decorator pattern via
following example in which we will decorate a shape
with some color without alter shape class.
Decorator pattern
 This is a pattern which attaches additional
responsibilities to an object dynamically.
 Decorators provide a flexible alternative to
sub classing for extending functionality.
 Decorator pattern achieves a single objective of
dynamically adding responsibilities to any
object.
Example Decorator
 When there is an interface where different
implementations can provide different
features, let each implementation stand on its
own.
 But implement them such that, at some point
during their work, they hand control over to
another instance of the same interface.
 Consider a case of a pizza shop.
 In the pizza shop they will sell few pizza varieties
and they will also provide toppings in the menu.
 Now imagine a situation wherein if the pizza
shop has to provide prices for each combination
of pizza and topping.
 Even if there are four basic pizzas and 8 different
toppings, the application would go crazy
maintaining all these concrete combination of
pizzas and toppings.
Facade pattern
 Facade pattern hides the complexities of the
system and provides an interface to the client
using which the client can access the system.
 This type of design pattern comes under
structural pattern as this pattern adds an interface
to existing system to hide its complexities.
 This pattern involves a single class which
provides simplified methods required by client
and delegates calls to methods of existing system
classes.
 The Facade Pattern provides a unified interface
to a set of interfaces in a subsytem.
 Facade defines a higher-level interface that
makes the subsystem easier to use.
 when I have several external or internal APIs and
I want to simplify the interface to access the
APIs
 when I want to protect my code against
unstable/on progress API.
Facade Design Pattern
 The facade design pattern is used to define a
simplified interface to a more complex
subsystem.
 The facade pattern is ideal when working
with a large number of interdependent classes,
 or with classes that require the use of multiple
methods, particularly when they are
complicated to use or difficult to understand
 Consider how a hospital’s computer systems might
get at various observations they have made about a
patient.
 You could have a patient class with attributes for
all the different types of observations (height,
blood type, heart rate, etc) but there would be
thousands of such attributes:
 too many to have as attributes of a patient class.
 So we can get around this by using the Observation
and Measurement patterns from measurement.
 Thus is we record a person is breathing at a rate of 23
breaths a minute we should be able to automatically
make the qualitative statement that that is a fast
breathing rate.
 For the purposes of our discussion we want to be able
record quantitative (height, 6 feet) and qualitative
(blood group A) statements about the patient.
 We also want to be able to assign qualitative statements
depending on a measurement.
 Thus is we record a person is breathing at a rate of 23
breaths a minute we should be able to automatically
make the qualitative statement that that is a fast
breathing rate
Flyweight pattern
 Flyweight pattern is primarily used to reduce the number
of objects created and to decrease memory footprint and
increase performance.
 This type of design pattern comes under structural pattern
as this pattern provides ways to decrease object count
thus improving the object structure of application.
 Flyweight pattern tries to reuse already existing similar
kind objects by storing them and creates new object when
no matching object is found.
 The Flyweight pattern was created to avoid this problem
and optimize performance.
 A flyweight is an object that minimizes memory use by sharing as much data as
possible with other similar objects;
 it is a way to use objects in large numbers when a simple repeated representation
would use an unacceptable amount of memory.
 The Flyweight Pattern is designed to control such kind of object creation and
provides you with a basic caching mechanism.
 It allows you to create one object per type (the type here differs by a property of
that object), and if you ask for an object with the same property (already created),
it will return you the same object instead of creating a new one.
For example
 We will demonstrate this pattern by drawing 20 circles of different locations
but we will create only 5 objects.
 Only 5 colors are available so color property is used to check already
existing Circle objects.
 Flyweight design pattern is used to minimize the memory usage with the
help of an object that shares as much data as possible with other similar
objects.
 The X-programming site allows users to
create and execute programs using their
favorite programming language.
 It provides you with plenty of programming
language options. You choose one, write a
program with it and execute it to see the
result.

Proxy Pattern
In proxy pattern, a class represents functionality of
another class.
 This type of design pattern comes under structural pattern.
 In proxy pattern, we create object having original object
to interface its functionality to outer world.
 For example:
 We are going to create an Image interface and concrete
classes implementing the Image interface. 
 ProxyImage is a a proxy class to reduce memory footprint
of RealImage object loading.
When to Use Proxy
 When we want a simplified version of a
complex or heavy object.
 When the original object is present in
different address space, and we want to
represent it locally.
 when we want to add a layer of security to the
original underlying object to provide
controlled access based on access rights of the
client.
Proxy Pattern
 The basic concept of a Proxy Pattern is that you
have a class functioning as an interface to a 
resource that is either remote or too large to
duplicate. 
Behavioural Pattern
 These design patterns are specifically
concerned with communication between
objects.
 Behavioural pattern are used to deal with
assignment of responsibility of object and
communication between the objects.
 Remote Application
 In software engineering, 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.
 For Example in Remote Application
Chain Responsibility Pattern
 It will creates a chain of receiver objects for a
request.
 This pattern decouples sender and receiver of a
request based on type of request.
 This pattern comes under behavioral patterns.
 In this pattern, normally each receiver contains
reference to another receiver.
 If one object cannot handle the request then it
passes the same to the next receiver and so on.
 A specific, logical requirement is passed into the chain
and is checked against each object in the set, in order,
 until a suitable match is found that meets the needs of
the particular requirement.
 For example:publishing company and we have a series
of books we want to publish. Each book is assigned a
type of cover (paperback, digital, or hard cover), along
with an estimated publishing cost.
 We’ll create a list of employees with varying authority
levels (CEO, President, CFO, etc), and assign each
employee a set of specifications that will determine
what types of books that employee is qualified to
approve for publication
 Finally, with everything in place, we can loop
through each book and run up the chain
responsibility of each employee, checking
whether he or she has the proper authority to
publish that book.
 If so, publication occurs, and if not, the next
employee up the chain is checked for
authority.
For example
 We have created an abstract
class AbstractLogger with a level of logging.
 Then we have created three types of loggers
extending the AbstractLogger.
 Each logger checks the level of message to its
level and print accordingly otherwise does not
print and pass the message to its next logger.
Command pattern
 Command pattern is a data driven design pattern and
falls under behavioral pattern category.
 A request is wrapped under an object as command and
passed to invoker object.
 Invoker object looks for the appropriate object which
can handle this command and passes the command to
the corresponding object which executes the command.
 As the name suggests it is related to actions and events
in an application.
 
Problem statement:
 Imagine a scenario where we have a web page
will multiple menus in it.
 One way of writing this code is to have multiple
if else condition and executing the actions on
each click of the menu.
 
Benefits:
 Command pattern helps to decouple the invoker
and the receiver.
 Receiver is the one which knows how to perform
an action.
 A command should be able to implement undo
and redo operations.
 This pattern helps in terms of extensibility as we
can add new command without changing
existing code.
Drawback:
 The main disadvantage of the Command pattern
is the increase in the number of classes for each
individual command.
 These items could have been also done through
method implementation.
 However the command pattern classes are more
readable than creating multiple methods using if
else condition.
For Example
 We have created an interface Order which is acting as
a command. We have created a Stock class which acts
as a request. We have concrete command
classes BuyStock and SellStock implementing Order int
erface which will do actual command processing. A
class Broker is created which acts as an invoker object.
It can take and place orders.
 Broker object uses command pattern to identify which
object will execute which command based on the type
of command. CommandPatternDemo, our demo class,
will use Broker class to demonstrate command pattern.
Interpreter pattern
 Interpreter pattern provides a way to evaluate
language grammar or expression.
 This type of pattern comes under behavioral
pattern.
 This pattern involves implementing an
expression interface which tells to interpret a
particular context.
 This pattern is used in SQL parsing, symbol
processing engine etc.
For Example
 We are going to create an
interface Expression and concrete classes
implementing the Expression interface. A
class TerminalExpression is defined which acts
as a main interpreter of context in question.
Other classes OrExpression, AndExpression are
used to create combinational expressions.
 InterpreterPatternDemo, our demo class, will
use Expression class to create rules and
demonstrate parsing of expressions.
Iterator pattern
 Iterator pattern is very commonly used design
pattern in Java and .Net programming
environment.
 This pattern is used to get a way to access the
elements of a collection object in sequential
manner without any need to know its underlying
representation.
 Iterator pattern falls under behavioral pattern
category.
 Interpreter design pattern is one of
the behavioral design pattern.
 Interpreter pattern is used to defines a
grammatical representation for a language and
provides an interpreter to deal with this grammar.
 MP3 player control is a good example of an
iterator.
 The user doesn't mind how to view their list
of songs, once they get to see them somehow.
 In older mp3 players, this was done using
simple forward and back buttons.
 With the iPod this changed to the wheel
navigation concept.
 The iPhone moves this on further to use swipe
movements.
For Example
 We're going to create a Iterator interface which
narrates navigation method and
a Container interface which retruns the iterator .
Concrete classes implementing
the Container interface will be responsible to
implement Iteratorinterface and use it
 IteratorPatternDemo, our demo class will
use NamesRepository, a concrete class
implementation to print a Names stored as a
collection in NamesRepository
Mediator pattern
 Mediator pattern is used to reduce
communication complexity between multiple
objects or classes.
 This pattern provides a mediator class which
normally handles all the communications
between different classes and supports easy
maintenance of the code by loose coupling.
 Mediator pattern falls under behavioral pattern
category.
 great example of mediator pattern where the
airport control room works as a mediator for
communication between different flights.
For Example
 We are demonstrating mediator pattern by example
of a chat room where multiple users can send
message to chat room and it is the responsibility of
chat room to show the messages to all users.
 We have created two
classes ChatRoom and User. User objects will
use ChatRoom method to share their messages.
 MediatorPatternDemo, our demo class, will
use User objects to show communication between
them.
Memento pattern
 Memento pattern uses three actor classes.
 Memento contains state of an object to be restored.
 Originator creates and stores states in Memento objects
and Caretaker object is responsible to restore object state
from Memento.
 Memento design pattern is used when we want to save the
state of an object so that we can restore later on.
 Memento pattern is used to implement this in such a way
that the saved state data of the object is not accessible
outside of the object, this protects the integrity of saved
state data.
 It can be used when a snapshot of an object’s state must
be captured,
 So that it can be restored to that state later & in situation
where explicitly passing the state of object would violate
encapsulation.
 For example:Whatsapp Group
 Whenever any person sends any message in the group,
all the people who are in the group get notified.
 Facebook : If one follows a post , he gets added to the
observers & any further comments on the same post ,
send a notification to all the other observers ; same as
twitter or any other social media follow use case .
Observer pattern
 Observer pattern is used when there is one-to-
many relationship between objects such as if one
object is modified, its dependent objects are to be
notified automatically.
 Observer pattern falls under behavioral pattern
category.
For Example
 Observer pattern uses three actor classes.
 Subject, Observer and Client.
 Subject is an object having methods to attach and
detach observers to a client object.
 We have created an abstract class Observer and a
concrete class Subject that is extending
class Observer.
 ObserverPatternDemo, our demo class, will
use Subject and concrete class object to show
observer pattern in action.
State pattern
 In State pattern a class behavior changes based
on its state.
 This type of design pattern comes under
behavior pattern.
 In State pattern, we create objects which
represent various states and a context object
whose behavior varies as its state object
changes.
 traffic signalling system which deals with the
conditions as below
 1. Green Light- It represents Move state of the
vehicles.
2. Yellow Light- It warns that signal is about
to change from green to red or red to green.
3. Red Light- It represents Stop state of the
vehicles.
For Example
 We are going to create a State interface
defining an action and concrete state classes
implementing the State interface. 
 Context is a class which carries a State.
 StatePatternDemo, our demo class, will
use Context and state objects to demonstrate
change in Context behavior based on type of
state it is in.
Null Object pattern
 In Null Object pattern, a null object replaces check of
NULL object instance.
 Instead of putting if check for a null value, Null Object
reflects a do nothing relationship.
 Such Null object can also be used to provide default
behaviour in case data is not available.
 In Null Object pattern, we create an abstract class
specifying various operations to be done, concrete classes
extending this class and a null object class providing do
nothing implementation of this class and will be used
seamlessly where we need to check null value.
Strategy Pattern
 Strategy pattern falls under the behavioral design
patterns.
 It’s very useful when you have an object which has
some behaviors that could be changed during the run-
time.
 For example:
 you have an application that tries to initiate a
payment of a customer, but the problem is, the
customer may choose to pay with paypal, or
with credit card, where each of them has a different
implementation.
 In Strategy pattern, a class behavior or its
algorithm can be changed at run time.
 This type of design pattern comes under behavior
pattern.
 In Strategy pattern, we create objects which
represent various strategies and a context object
whose behavior varies as per its strategy object.
 The strategy object changes the executing
algorithm of the context object.
Class Diagram
 A composition relationship between the customer and the payment interface,
where each payment method inherits setPayment method. The composition
relationship implies the idea of HAS-A relationship
Template pattern
 In Template pattern, an abstract class exposes
defined way(s)/template(s) to execute its
methods.
 Its subclasses can override the method
implementation as per need but the invocation is
to be in the same way as defined by an abstract
class.
 This pattern comes under behavior pattern
category.
For Example
 We are going to create a Game abstract class
defining operations with a template method
set to be final so that it cannot be overridden. 
 Cricket and Football are concrete classes that
extend Game and override its methods.
 TemplatePatternDemo, our demo class, will
use Game to demonstrate use of template
pattern.
Visitor pattern
 In Visitor pattern, we use a visitor class which
changes the executing algorithm of an element
class.
 By this way, execution algorithm of element can
vary as and when visitor varies.
 This pattern comes under behavior pattern
category.
 As per the pattern, element object has to accept
the visitor object so that visitor object handles the
operation on the element object.
  real world analogy always helps with the
understanding of a design pattern.
 One example I have seen for the Visitor
pattern in action is a taxi example, where the
customer calls orders a taxi, which arrives at
his door.
 Once the person sits in, the visiting taxi is in
control of the transport for that person. 
 Shopping in the supermarket is another
common example, where the shopping cart is
your set of elements.
 When you get to the checkout, the cashier
acts as a visitor, taking the disparate set of
elements (your shopping), some with prices
and others that need to be weighed, in order to
provide you with a total. 
For Example
 We are going to create a ComputerPart interface
defining accept
opearation.Keyboard, Mouse, Monitor and Computer a
re concrete classes
implementing ComputerPart interface. We will define
another interface ComputerPartVisitor which will
define a visitor class operations. Computeruses
concrete visitor to do corresponding action.
 VisitorPatternDemo, our demo class, will
use Computer and ComputerPartVisitor classes to
demonstrate use of visitor pattern.
MVC Pattern
 MVC Pattern stands for Model-View-Controller Pattern.
 This pattern is used to separate application's concerns.
 Model - Model represents an object or JAVA POJO
carrying data. It can also have logic to update controller
if its data changes.
 View - View represents the visualization of the data that
model contains.
 Controller - Controller acts on both model and view.
 It controls the data flow into model object and updates
the view whenever data changes.
 It keeps view and model separate.
For Example: Best Example RMI
 We are going to create a Student object acting as
a model.StudentView will be a view class which
can print student details on console
and StudentControlleris the controller class
responsible to store data in Student object and
update view StudentView accordingly.
 MVCPatternDemo, our demo class, will
use StudentController to demonstrate use of
MVC pattern.
Business Delegate Pattern
 Business Delegate Pattern is used to decouple
presentation tier and business tier.
 It is basically use to reduce communication or
remote lookup functionality to business tier
code in presentation tier code.
Business Delegate Pattern
 In business tier we have following entities.
 Client - Presentation tier code may be JSP, servlet or UI
java code.
 Business Delegate - A single entry point class for client
entities to provide access to Business Service methods.
 LookUp Service - Lookup service object is responsible to
get relative business implementation and provide business
object access to business delegate object.
 Business Service - Business Service interface. Concrete
classes implement this business service to provide actual
business implementation logic.
Composite Entity pattern
 Composite Entity pattern is used in EJB
persistence mechanism.
 A Composite entity is an EJB entity bean
which represents a graph of objects.
 When a composite entity is updated,
internally dependent objects beans get
updated automatically as being managed by
EJB entity bean.

Composite Entity pattern
Following are the participants in Composite Entity Bean.
 Composite Entity - It is primary entity bean. It can be coarse
grained or can contain a coarse grained object to be used for
persistence purpose.
 Coarse-Grained Object - This object contains dependent
objects. It has its own life cycle and also manages life cycle
of dependent objects.
 Dependent Object - Dependent object is an object which
depends on coarse grained object for its persistence lifecycle.
 Strategies - Strategies represents how to implement a
Composite Entity.
Data Access Object Pattern
 Data Access Object Pattern or DAO pattern is
used to separate low level data accessing API
or operations from high level business
services.
Data Access Object Pattern
 Following are the participants in Data Access Object
Pattern.
 Data Access Object Interface - This interface defines
the standard operations to be performed on a model
object(s).
 Data Access Object concrete class - This class
implements above interface. This class is responsible to
get data from a data source which can be database / xml
or any other storage mechanism.
 Model Object or Value Object - This object is simple
POJO containing get/set methods to store data retrieved
using DAO class.
Front Controller Design Pattern
 The front controller design pattern is used to
provide a centralized request handling
mechanism so that all requests will be handled
by a single handler.
 This handler can do the authentication/
authorization/ logging or tracking of request
and then pass the requests to corresponding
handlers
Front Controller Design Pattern
 Following are the entities of this type of design
pattern.
 Front Controller - Single handler for all kinds of
requests coming to the application (either web
based/ desktop based).
 Dispatcher - Front Controller may use a dispatcher
object which can dispatch the request to
corresponding specific handler.
 View - Views are the object for which the requests
are made.
Intercepting Filter Design Pattern
 The intercepting filter design pattern is used when
we want to do some pre-processing / post-
processing with request or response of the
application.
 Filters are defined and applied on the request before
passing the request to actual target application.
 Filters can do the authentication/ authorization/
logging or tracking of request and then pass the
requests to corresponding handlers.
Intercepting Filter Design Pattern
 Following are the entities of this type of design pattern.
 Filter - Filter which will performs certain task prior or
after execution of request by request handler.
 Filter Chain - Filter Chain carries multiple filters and
help to execute them in defined order on target.
 Target - Target object is the request handler
 Filter Manager - Filter Manager manages the filters
and Filter Chain.
 Client - Client is the object who sends request to the
Target object.
Service Locator Design Pattern
 The service locator design pattern is used when we
want to locate various services using JNDI lookup.
 Considering high cost of looking up JNDI for a service,
Service Locator pattern makes use of caching
technique.
 For the first time a service is required, Service Locator
looks up in JNDI and caches the service object.
 Further lookup or same service via Service Locator is
done in its cache which improves the performance of
application to great extent.
Service Locator Design Pattern
 Following are the entities of this type of design pattern.
 Service - Actual Service which will process the request.
Reference of such service is to be looked upon in JNDI server.
 Context / Initial Context - JNDI Context carries the reference
to service used for lookup purpose.
 Service Locator - Service Locator is a single point of contact
to get services by JNDI lookup caching the services.
 Cache - Cache to store references of services to reuse them
 Client - Client is the object that invokes the services via
ServiceLocator.
Transfer Object pattern
 The Transfer Object pattern is used when we want to pass data
with multiple attributes in one shot from client to server.
 Transfer object is also known as Value Object. Transfer Object
is a simple POJO class having getter/setter methods and is
serializable so that it can be transferred over the network.
 It does not have any behavior. Server Side business class
normally fetches data from the database and fills the POJO and
send it to the client or pass it by value.
 For client, transfer object is read-only. Client can create its
own transfer object and pass it to server to update values in
database in one shot.
Transfer Object pattern
 Following are the entities of this type of design
pattern.
 Business Object - Business Service fills the
Transfer Object with data.
 Transfer Object - Simple POJO having
methods to set/get attributes only.
 Client - Client either requests or sends the
Transfer Object to Business Object.
Command Pattern
 Command pattern falls under the behavioral design patterns

 It’s solution to a problem when an object has to perform


some commands during the run-time; we don’t know which
commands needs to be executed.
 You start separating those commands in encapsulated classes.
Each class is implementing an interface that has a method
called execute.
 It’s the same principle as in the stratgey pattern; separate
what varies from what stays the same.
Example: Read, Update, Delete Commands
 We have the invoker object represents the
admin, where the admin of the system can
perform different commands. We have
the command interface, where all commands
are inheriting from it.
 And we have the receiver object, which will
be used by the inheriting command sub
classes to perform the requested command.
Class Diagram
 A composition relationship between the admin and the
command Interface, where each command method
implements execute method.
State Pattern
 State pattern is a behavioral software design pattern.

 It’s used for the system that has different states to navigate
between them based on some interactions during the running
time.
 States are in form of objects, where each state object handles
a specific kind of user interaction.
 The interactions maybe external interactions from the users,
or internally from the system itself.
 Again, the same principle also applies here; separate what
varies from what stays the same. So, we need to encapsulate
these states as they will be changed during the run time.
Example: Microwave
 imagine that you have a microwave, that has an initial state called waiting,
and whenever the user press on start button, it moves to working state, and
at this point the user can either pause or stop the microwave.
 In case of pause it will move to a third state called paused, and in case of
stop, it will revert back to waiting state.
 We start creating a class for each state, each of these states will inherit
from an interface called State.
Class Diagram
 A composition relationship between the microwave and the state interface.
 The microwave class handles the interactions of the user, by asking the current
state object to handle this interaction, which in turn navigate from one state to
another (if needed). So, we only care about creating an instance from the
microwave class.
 This decreases the dependency, and the user will only care about the Microwave
rather than each state.
A pattern has in general 4 essential
elements:
• Pattern name
• Problem
• Solution
• Consequences
Pattern Name
• A handle used to describe a design problem, its
solutions and its consequences in a word or two
• Increases design vocabulary
• Makes it possible to design at a higher level of
abstraction
• Enhances communication
• But finding a good name is often hard
Problem
• Describes when to apply the pattern
• Explains the problem and its context
• Might describe specific design problems or
class or object structures
• Sometimes contains a list of conditions that
must be met before it makes sense to apply
the pattern
Solution
• Describes the elements that make up the
design, their relation-ships, responsibilities
and collaborations
• Doesn’t describe a particular concrete design
or implemen-tation
• Abstract description of design problems and
how the pattern solves it
Consequences
• Results and trade-offs of applying the pattern
• Critical for evaluating design alternatives and
for understan- ding the costs and benefits of
applying the pattern
• Includes the impacts of a pattern on a
system’s flexibility, ex- portability
Design Patterns Are Not
• Designs that can be encoded in classes and
reused as is (i.e.linked lists, hash tables)
• Complex domain-specific designs (for an
entire application or subsystem)
Design Pattern are:
 “Descriptions of communicating objects and
classes that are customized to solve a general
design problem in a particular context.”
Where Design Patterns
Are Used
• Design patterns can be implemented in
object-oriented pro-gramming languages
rather than procedural languages.
• In procedural languages design patterns for
Inheritance, Poly- morphism and
Encapsulation would be defined
How to Describe Design Patterns

• Graphical notation is not sufficient


• To reuse design decisions, alternatives and
trade-offs that led to the decisions are
important
• Concrete examples are also important
Classification
 Design patterns can be classified by two criteria:
1. Purpose
 What a pattern does (creational, structural
or behavioral)
2. Scope
 Whether the pattern applies primarily to
classes (static, compile-time) or to objects
(dynamic, run-time)
How Design Patterns Solve
Design Problems
 Design patterns solve many of the day-to-day
problems object-oriented designers face, and
in many different ways.
 Here are several of these problems and how
design patterns solve them.
Finding Appropriate Objects
• Hard part of object-oriented design is
decomposing a system into objects
  Encapsulation, granularity,
dependency, flexibility, performance, …
• Design Patterns help identifying less obvious
abstractions and the objects that can capture
them
Determining Object Granularity
• Objects can vary tremendously (very) in size
and number
• Design patterns address this also i.e.
describing how to decompose an object into
smaller objects
Specifying Object Interfaces
• An object’s interface characterizes the complete set of requests
that can be sent to the object
• A type = particular interface
• Subtypes inherit the interfaces of its super types
• Run-time association to an object and one of its operationsis
known as dynamic binding
  Polymorphism
• Design patterns help defining the interfaces by identifying the
key elements and the kind of data that gets sent across an
interface
• A design pattern might also tell what not to put in an inter- face
Specifying Object Implementations (1)
• An object’s implementation is defined by its
class
• Objects are created by instantiating a class
• A subclass inherits the definition of all data
and operations from the parentclass
• Abstract classes define common interfaces,
but cannot be instantiated
Specifying Object Implementations (2)
 Class vs. Interface Inheritance:
• Distinction between class and type
• Many design patterns depend on this distinction

 Programming to an Interface, not an Implementation:


• There two benefits from manipulating objects solely in terms of the
interface defined by abstract classes
1. clients remain unaware of the specific types they use, as long as the
objects adhere to the interface that clients expect
2. Clients remain unaware of the classes that implement these objects,
clients only know about the abstract class(es) defining the interface

 Creational Patterns assure, that the system is written in terms of


interfaces,not implementations
Putting Reuse Mechanism to Work (1)
 Inheritance vs. Composition:
 Class inheritance = white-box-reuse = compile-time
 Class composition = black-box-reuse = run-time
 Favor object composition over class inheritance
• any object can be replaced at run-time by another
 as long as it has the same type
  Fewer implementation dependencies
• Object composition helps keeping each class en-
 capsulated and focused on one task

 Disadvantage: More objects and the system behavior will depend


on their relationships
Putting Reuse Mechanism to Work (2)
 Delegation:
• A way of making composition as powerful as inheritance
• A receiving object delegates operations to its delegate
  Easy to compose behaviors at run-time
  Disadvantage: Makes the software harder to
 understand
  It can make software more complicate
 than it simplifies

 Inheritance vs. Parameterized Types:


• Defining a type without specifying all other types it uses
 (i.e. templates in C++)
• Also a way to compose behavior in object-oriented systems
Relating Run-Time and Compile-Time
Structures
• An object-oriented program's run-time structure often bears little resem-blance to its
code structure
• code structure frozen at compile-time
• run-time structure consists of rapidly changing networks of com-municating
objects
• Aggregation = an object is being part of another object
• Acquaintance = an object merely knows of another object
• With Acquaintance much looser coupling of objects is
 possible
 Relationships between objects and their types must be designed with
great care, because they determine how good or bad a run-time
structure is
• Many design patterns capture the distinction between compile-time and run-time
structures explicitly
Designing for Change
• The key for maximizing reuse lies in anticipating
new require-ments and in designing the system that
they can evolve accor-dingly
• System design must take change into its account
• Redesign affects many parts of the software system
• Design patterns help assuring that a system can
change in specific ways by providing designs that
add more flexibility to software
Design Patterns in Application
Programs
• In an application program usually internal reuse, maintainabi-
lity and extension are high priorities
• Design patterns that reduce dependencies can increase
internal reduce
• They can make a system more maintainable when they’re
used to limit platform dependencies and to layer a system
• They enhance extensibility by showing how to extend class
hierarchies and how to exploit object composition
Design Patterns in Toolkits
• A toolkit is a set of related and reusable classes designed to
provide useful, general-purpose functionality
• They are the object-oriented equivalent of subroutine libraries
• Toolkit design is harder than application design because they
have to work in many applications
• The toolkit writer doesn’t know what those applications will
be or their special needs
 Avoid assumptions that can limit flexibility, applicabili-ty
and effectiveness
Design Patterns in Frameworks
• A framework is a set of operating classes that make up a
usable design for a special class of software
• It dictates the architecture of an application
• They emphasize design reuse over code reuse
• Applications can be built faster and have similar structures
• Applications are very dependent on the framework
• Design patterns and frameworks are very similar, but they
 differ in three major ways
1. Design patterns are more abstract then frameworks
2. Design patterns are smaller architectural elements than
frameworks
3. Design patterns are less specialized than frameworks
How to Select a Design Pattern
 Depending on the catalogue used there are several
approaches:
• Consider how design patterns solve design
problems
• Scan intent section
• Study how patterns interrelate
• Study patterns of like purpose
• Examine a cause of redesign
• Consider what should be the variable in the design
How to Use a Design Pattern
 Once a design pattern is picked the design pattern could be applied:
 Read the pattern once through an overview
• Go back and study the structure, participants and collabo-
ration sections
• Look at the sample code section to see a concrete example of
the pattern in code
• Choose names for patterns participants that are meaningful in
the application context
• Define the classes
• Define application-specific names for operations in the pattern
• Implement the operations to carry out the responsibilities in
the pattern
How Not to Use a Design Pattern
• They should not be applied accidentally/
bychance
• Often they achieve flexibility and variability
by introducing additional levels of indirection
 They complicate design and cost performance
 A design pattern should only be applied when the
flexibility it affords is actually needed
• The consequences sections are helpful when
evaluating a pattern’s benefits and liabilities
Conclusion
• Cataloging design patterns is important, it
gives standard names and definitions for the
techniques we use
• If design patterns in software are not studied
it will not be able to improve them or to come
up with new ones
What to Expect from Design Patterns

 There are several ways design patterns can affect


the way object-oriented software is designed:
• A common design vocabulary
• A documentation and learning aid
• An adjunct to existing methods
• A target for refactoring
A Common Design Vocabulary
• Computer scientists name and catalog algorithms
and data structures, but often they don’t name
other kinds of patterns
• Design patterns provide a common vocabulary to
use to com-municate, document and explore
design alternatives
• They make a system less complex by making it
possible to talk about it at a higher level of
abstraction
A Documentation and Learning Aid
• People learning object-oriented programming often complain
that systems use inheritance in convoluted ways and it is
difficult to follow the control flow
 Many of the systems use design patterns, so they become
easier to understand
• Design patterns also make designing software easier by
providing solutions for common problems
• Describing a system in terms of the design patterns it uses
makes it easier to understand, otherwise people have to
reverse-engineer to unearth the patterns
An Adjunct to Existing Methods
• Object-oriented design methods are supposed to promote
good design, but they haven’t been able to capture the
experience of expert designers
• Design patterns provide a way to describe more of the “why”
of a design and not just record the results of decisions
• Design patterns are especially useful in turning an analysis
model into an implementation model
A Target for Refactoring (1)
• One problem in developing reusable software is that it often has to be
reorganized or refactored, design patterns help determining how to
reorganize a design and reduce the amount of refactoring
• Lifecycle of object-oriented software:
1. Prototyping
 Software is brought to life through rapid prototyping and
incremental changes until it meets an initial set of requirements
and reaches adolescence, the main kind of reuse is white-box-
reuse
2. Expansionary
 The software goes through an expansionary phase to meet new
requirements until it becomes too inflexible and arthritic
A Target for Refactoring (2)
3. Consolidation
 Software becomes more general, block-box-reuse replaces
white-box-reuse

• This cycle is unavoidable, but using design patterns prevents later


refactoring
 Refactoring = Tearing apart classes into special- and general-purpose
components, moving operations up or down the class hierarchy and
rationalizing to reorganize software in the consolidation phase
Two Examples
• Two design patterns and an example how they
could be used:
1. Singleton
 Ensure a class only has one instance and provide a
global point of access to it
2. Observer
 Define a one-to-many dependency between objects so
that when one object changes state, all its dependents
are notified and updated automatically
Singleton
• It’s important for some classes to have exactly one instance
• The best solution is to make the class itself responsible for keeping track
of its sole instance
• The class can ensure that no other instance can be created by intercepting
requests to create new objects and it can provide a way to access the
instance
• It was used to simulate parallelism in a system to avoid communication-
and synchronization problems
• It activates specific methods of objects periodically
• Only one instance of the class must exist
• To ensure this the singleton pattern is used
Design pattern example
Some examples of Design
Patterns
Template for discussion
 Non-software example.
 Pattern intent.
 Software counterpart example.

Non-software examples are derived from paper


& PPT – “Non-software examples of software
design patterns” (OOPSLA 97).
Facade (Non software example)

Provide a unified
interface to a set
of interfaces in a
subsystem.
Facade (Software counterpart)
Flyweight (Non software example)

Use sharing to
support large
numbers of fine-
grained objects
efficiently
Flyweight (Software counterpart)

Memory
Chain of Responsibility (Non software
example)

Chain the
receiving objects
and pass the
request along the
chain until an
object handles it.
Chain of Responsibility (Software
counterpart)

Internet

Login Password Balance


page checking statement
Memento (Non software example)

Externalize
object’s state so
that object can be
restored to this
state later.
Memento (Software counterpart)
Observer (Non software example)

When an object
changes its state,
all its dependants
are notified.
Observer (Software counterpart)

Internet

Cricinfo
Server
Adapter (Non software example)

Convert the
interface of a
class into another
Interface clients
expect.
Adapter (Software counterpart)

Java Native
Java module C++ module
Interface (JNI)
Builder (Non software example)

Separate the construction


process of a complex object
from its representation so
that the same construction
Process can create different
representations.
Builder (Software counterpart)
Compiler process

Lexical Syntax Semantic Intermediate Interpret


analysis analysis analysis code ation

Java Compiler

Java Java Semantic Java byte


JVM
Lexer Parser analysis code

Python Compiler

Python Python Semantic Python byte


PVM
Lexer Parser analysis code
Iterator (Non software example)

Provide a way to
access the
elements of a set
sequentially.
Iterator (Software counterpart)
Interpreter (Non software example)

Interpreter interprets
the sentences in a
language based
on its grammar.
Interpreter (Software counterpart)

In Gtalk/Yahoo messengers
:-) is interpreted as 
:-( is interpreted as 
Broker (Non software example)
Broker component is
responsible for
coordinating
communication
between clients and
remote servers.
Broker (Software counterpart)
Publisher-Subscriber (Non software
example)

Publishers register
themselves to a
broker and
subscribers discover
publisher from broker.
Publisher-Subscriber (Software
counterpart)
Forums (e.g. movie forums)
Proxy (Non software example)

Provide a surrogate or
placeholder for
another object to
control access to it.
Proxy (Software counterpart)
Strategy (Non software example)

A Strategy defines a set of algorithms that can be


used interchangeably.
Strategy (Software counterpart)

Multiple
interchangeable
weapons available to
attack an enemy.
Mediator (Non software example)
Loose coupling
between colleague
objects is achieved by
having colleagues
communicate with the
Mediator, rather than
one another.
Mediator (Software counterpart)

Gtalk Server
Master-Slave (Non software example)
Master component
distributes work to
identical slave
components and
computes a final
result from the results
when the slaves
return.
Master-Slave (Software counterpart)
Movie players High-resolution Game players

Graphics
partitioning
Layers (Software example)

Layers structure applications whose dominant


characteristic is a mix of low- and high- level issues.
MVC (Software example)

MVC structures interactive applications.


Microkernel (Software example)

Microkernel separates the variant and non-variant


parts of a product-line application.
Reflection (Software example)

Reflection pattern provides a mechanism for changing


structure and behavior of a system dynamically.
State (Software example)
An object alters its
behavior when its
internal state
changes.
Template Method (Software example)
Event handling in Java GUI
components is unimplemented.

Define the skeleton of an


algorithm in an operation,
deferring some steps to
subclasses.
Design Patterns
 Are the answer to a question that commonly
arises “How can I … ?”
 Patterns record successful solutions in software
development for sharing between projects.
 Gang of Four (GoF) Gamma, Helm, Johnson,
Vlissides, - founders of movement.
 Gamma et al, Design Patterns: Elements of
Reusable Object-Oriented Software, Addison
Wesley, 1995.
Patterns solve software structural problems like:
 Abstraction,
 Encapsulation
 Information hiding
 Separation of concerns
 Coupling and cohesion
 Separation of interface and implementation
 Single point of reference
 Divide and conquer
Patterns also solve non-functional problems like
 Changeability
 Interoperability
 Efficiency
 Reliability
 Testability
 Reusability
Types of Pattern
There are 3 types of pattern …
 Creational: address problems of creating an
object in a flexible way. Separate creation, from
operation/use.
 Structural: address problems of using O-O
constructs like inheritance to organize classes and
objects
 Behavioral: address problems of assigning
responsibilities to classes. Suggest both static
relationships and patterns of communication
(use cases)
Patterns, Architectures & Frameworks
 There can be confusion between patterns, architectures and
frameworks.
 Let’s try to distinguish them:
 Architectures model software structure at the highest
possible level, and give the overall system view. An
architecture can use many different patterns in different
components
 Patterns are more like small-scale or local architectures
for architectural components or sub-components
 Frameworks are partially completed software systems that
may be targeted at a particular type of application. These
are tailored by completing the unfinished components.
Summary of Differences
 Patterns are more general and abstract than
frameworks.
 A pattern is a description of a solution, not a
solution itself.
 A pattern cannot be directly implemented.
 An implementation is an example of a pattern.
 Patterns are more primitive than frameworks.
 A framework can employ several patterns.
Catalogues & Languages
 Patterns are grouped into catalogues and
languages
 A catalogue is group of patterns that may be
reasonable to use together
 A language is a more closely related
collection useful for a common problem
domain, e.g. Banking
Pattern Templates
 Name: meaningful text that reflects the problem, e.g. Bridge,
Mediator, Flyweight
 Problem addressed: intent of the pattern, objectives achieved
within certain constraints
 Context: circumstances under which it can occur, used to
determine applicability
 Forces: constraints or issues that solution must address, forces
may conflict!
 Solution: the static and dynamic relationships among the
pattern components. Structure, participants, collaboration.
Solution must resolve all forces!
Pattern: Singleton (Creational)
Name: Singleton
Problem:
How can we guarantee that one and only one instance of a class can be created?
Context: In some applications it is important to have exactly one instance of a class,
e.g. sales of one company.
Forces: Can make an object globally accessible as a global variable, but this violates
encapsulation. Could use class (static) operations and attributes, but polymorphic
redefinition is not always possible.
Solution:
Create a class with a class operation getInstance().
When class is first accessed, this creates relevant object instance and returns object
identity to client.
On subsequent calls of getInstance(), no new instance is created, but identity of
existing object is returned.
Singleton Structure
Singleton Object identifier for singleton
instance, class scope or static
-uniqueInstance
-singletonData Returns object identifier for
unique instance, class-scope
+getInstance( ) or static
+getSingletonData( )
+singletonOperation( )
-Singleton( ) Private constructor only accessible
via getInstance()

getInstance( ) {
if ( uniqueInstance == null )
{ uniqueInstance = new Singleton( ) }
return uniqueInstance
}
Example: Code

Class Singleton {
private static Singleton uniqueInstance = null;
private Singleton( ) { .. } // private constructor
public static Singleton getInstance( ) {
if (uniqueInstance == null)
uniqueInstance = new Singleton();
// call constructor
return uniqueInstance;
}
}
Comments
 To specify a class has only one instance, we make
it inherit from Singleton.
+ controlled access to single object instance through
Singleton encapsulation
+ Can tailor for any finite number of instances
+ namespace not extended by global variables
- access requires additional message passing
- Pattern limits flexibility, significant redesign if
singleton class later gets many instances
Pattern: Façade (Structural)
Name: Façade
Problem:
How can we access a large number of classes
with a complex internal interaction in a
simple but safe way?
Solution: Introduce a dedicated interface class
that simplifies the view of the class collection.
Facade Structure
Facade
subsystem classes
<<façade>>
SecurityManager Pattern Name
+addAccessRight()
+addActor()
+addActorRole()
+removeActor()

AccessRight
ActorRole

+addAccessRight()
+addActorRole()

Actor

+addActor()
+removeActor()
+changeSalary() Method not in Facade
Comments
 Clients communicate with the subsystem by sending requests to
Façade which forwards them to the appropriate subsystem
object(s).
 Although subsystem objects perform actual work, Façade may
have to translate its interface to subsystem interfaces.
 Clients that use the Façade don’t have to access its subsystem
objects directly.
 Usually only one Façade object is required. Thus a Façade
object is often a singleton.
 Factory pattern can be used with Façade to provide an interface
for creating subsystem objects in a subsystem independent way.
 Factory can also be used as an alternative to Façade to hide
platform-specific classes.
 Mediator pattern is similar to Façade in abstracting functionality
of classes.
Pattern: Mediator (Behavioral)
Problem:
How can we deal with two or more classes which sometimes
interact, but can also be used separately?
Solution: Mediator promotes loose coupling by keeping objects
from referring to one another explicitly. Put each interaction
between objects in a separate (Mediator) class. This class
should have references to the objects.
 A pattern for two objects which exist independently but have
some coupling. This coupling is placed in its own class.
 Used by e.g. ActionListener in graphics which couples
together two graphical objects, e.g. window & button
Mediator Structure

1 mediator
Mediator Colleague

*
ConcreteMediator Concrete Concrete
Colleague1 Colleague2
*

Colleagues send and receive requests from a Mediator object. The mediator implements
the cooperative behavior by routing requests between appropriate colleagues.
Pattern: Observer (Behavioral)
Name: Observer
Problem: Define a one-to-many dependency
among objects so that when one object changes
state, all of its dependents are notified and
updated automatically.
Solution: MVC, but refined by separating abstract
from concrete subjects and observers
Subject
*
Observer
attach(Observer)
detach(Observer)
notify() for all o in Update()
observers {

o.update( ) }

ConcreteObserver
*
ConcreteSubject observerState
update()

subjectState()
return observerState =
getState()
setState()
subjectStat subject.getState(
e )
 ConcreteSubject notifies its observers whenever a change
occurs that could make its observers state inconsistent with
its own
 After being informed of change, a ConcreteObserver
queries the subject to reconcile its state with subjects.
 Observer object that initiates change request postpones its
update until it gets notification from subject. Notify() is not
always called by subject. Can be called by an observer, or
any other object.
 Pattern is well known, has wide range of variants
aConcrete aConcrete aConcrete
Subject: Subject: Subject:

setState( )

notify( )

update( )

getState( )

update( )
getState( )
Command
Name: Command
Problem: Need a flexible organization for methods that allows them
to be context sensitive in a structured way.
Solution: Place behaviour /operation in an own class instead of in a
method.
 Example:

 Undo. It’s difficult to undo effects of an arbitrary method.


Methods vary over time.

 Choose menu option. Whether an option can be chosen at any


time depends on many factors.
Command Structure
1
Client Invoker Command
Execute()

1
receiver
Receiver
ConcreteCommand
Action() Receiver.Action()
Execute()
State
 Client creates a ConcreteCommand object
and specifies its receiver.
 An Invoker object stores the
ConcreteCommand object
 The invoker issues a request by calling Execute
on the command. When commands are
undoable, ConcreteCommand stores state for
undoing the command before invoking Execute
 ConcreteCommand object invokes operations
on its receiver to carry out request
aClient aCommand anInvoker aReceiver

new Command(aReceiver)

storeCommand(aCommand)

Execute()

Action()
Guidelines Checklist
 Is there a pattern that addresses my problem?
 Does the pattern provide an acceptable solution?
 Is there a simpler solution? (pattern overuse)
 Is the context of the pattern consistent with my
problem?
 Are the consequences of using the pattern
acceptable?
 Are there forces in my environment that conflict
with the use of the pattern?
Benefits and Dangers
+ support software reuse
+ language for discussing high-level problems
+ access to experience and knowledge
- limit creativity?

- needs a culture of reuse

- needs organisational education


04/06/22 287

You might also like