Professional Documents
Culture Documents
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
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
System Design:
Organize into subsystems based on analysis
structure and propose architecture
OO Design
(Booch) design then
program
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.
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 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
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
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)
Java Compiler
Python Compiler
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)
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)
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:
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?