Unit III Design Patterns
Unit III Design Patterns
UNIT-III
INTRODUCTION
• Design Patterns are commonly accepted
solutions to some problems that often
recur as sub problems while designing
different applications.
• They are solutions to software design
problems that you can find in a real-world
application.
• A Design Pattern is not a code that is
ready to be used in your application,
but it is a model that you can use to
solve a problem.
INTRODUCTION
• Design patterns are language neutral, so
they can be applied to any language that
supports object-orientation.
• Design Patterns represent the best
practices used by experienced object-
oriented software developers.
• While working out the design solution to
a problem, experienced designers
consciously reuse solutions that they
might have worked out in past.
INTRODUCTION
• These patterns solve specific design
problems and make object-oriented
designs more flexible, elegant, and
ultimately reusable.
• A designer who is familiar with such
patterns can apply them immediately to
design problems without having to
rediscover them.
HISTORY
• The concept of patterns was first described
by Christopher Alexander in
A Pattern Language: Towns, Buildings, Cons
truction
.
• The book describes a “language” for
designing the urban environment.
• They may describe how high windows
should be, how many levels a building
should have, how large green areas in a
neighbourhood are supposed to be, and so
on.
HISTORY
• The idea was picked up by four authors:
Erich Gamma, John Vlissides, Ralph
Johnson, and Richard Helm.
• In 1994, they published
Design Patterns: Elements of Reusable
Object-Oriented Software
, in which they applied the concept of
design patterns to programming.
HISTORY
• The book featured 23 patterns solving
various problems of object-oriented
design and became a best-seller very
quickly.
• Due to its lengthy name, people started
to call it “The book by the gang of four”
which was soon shortened to simply “the
GoF book”.
DESIGN PATTERN
• Christopher Alexander says,
"Each pattern describes a problem which
occurs over and over again in our
environment, and then describes the
core of the solution to that problem, in
such a way that you can use this solution
a million times over, without ever doing it
the same way twice".
DESIGN PATTERN
• In general, a pattern has four essential
elements
PATTERN NAME
PROBLEM
SOLUTION
CONSEQUENCES
DESIGN PATTERN
PATTERN NAME
• The pattern name is a handle we can
use to describe a design problem, its
solutions, and consequences in a word
or two.
• Naming a pattern immediately increases
our design vocabulary.
• It lets us design at a higher level of
abstraction.
DESIGN PATTERN
PROBLEM
• The problem describes when to apply
the pattern.
• It explains the problem and its context. It
might describe specific design problems
such as how to represent algorithms as
objects.
• Sometimes the problem will include a list
of conditions that must be met before it
makes sense to apply the pattern.
DESIGN PATTERN
SOLUTION
• The solution describes the elements that
make up the design, their relationships,
responsibilities, and collaborations.
• The solution doesn't describe a particular
concrete design or implementation, because a
pattern is like a template that can be applied in
many different situations.
• Instead, the pattern provides an abstract
description of a design problem and how a
general arrangement of elements (classes and
objects in our case) solves it.
DESIGN PATTERN
CONSEQUENCES
• The consequences are the results and
trade-offs of applying the pattern.
• Though consequences are often
unvoiced when we describe design
decisions, they are critical for evaluating
design alternatives and for understanding
the costs and benefits of applying the
pattern.
TYPES OF PATTERNS
• Different types of patterns have been
identified for use in different stages of
design.
• Starting from use in very high-level
designs termed as architectural designs,
pattern solutions have been defined for
use in concrete designs, and even in
code.
TYPES OF PATTERNS
Architectural patterns:
• The architectural patterns provide
solutions to problems that are identifiable
while carrying out architectural (or very
high-level) designs.
• Architectural design concerns designing
the overall structure of a software
System.
TYPES OF PATTERNS
Architectural patterns:
• Architectural designs cannot directly be
translated to code, but form the basis for
more detailed design.
• Architectural designs are usually
constructed for very large problems.
• Therefore, architectural patterns are
relevant while working out the high-level
solutions to very large problems.
TYPES OF PATTERNS
Design patterns:
• A design pattern usually suggests a
scheme for structuring the classes in a
design solution and also defines the
interactions among those classes.
• Design pattern solutions are typically
described in terms of classes, their
instances, their roles and collaborations.
TYPES OF PATTERNS
Idioms:
• Idioms are low-level patterns that are
programming language-specific.
• The most basic and low-level patterns
are often called idioms.
• They usually apply only to a single
programming language.
Comparison of different types
of Patterns
• The main differences among the three kinds of
patterns discussed lie in the levels of abstraction and
details they deal with.
• Architectural patterns are high-level strategies that
concern the overall solutions to large-scale problems.
• Design patterns are solutions for specific parts of
medium-scale problems and recommend certain
structure and behaviour for the participating entities.
• Idioms are paradigm-specific and language-specific
programming solutions that recommend using
appropriate code segments for solving low level
programming problems.
Pros of Design Patterns
The following are the main strengths of design
patterns:
•Design patterns provide a common vocabulary
that helps to improve communication among the
developers.
•Design patterns helps to capture and
disseminate expert knowledge.
•Use of design patterns helps designers to
produce designs that are flexible, efficient, and
easily maintainable.
Pros of Design Patterns
• Design patterns guide developers to arrive at
correct design decisions and help them to
improve the quality of their designs.
• Design patterns help to reduce the number of
design iterations, and thereby improve a
designer’s productivity. The selection and use
of design patterns are largely based on the
subjective decisions of the designer, and only
some general guidelines are available
regarding the pattern to use while solving a
design problem.
Cons of Design Patterns
Important shortcomings of design patterns are
the following:
•Design patterns do not directly lead to code
reuse. A design pattern is usually tailored for a
specific circumstance of reuse, and therefore it is
difficult to associate a fixed code segment with a
pattern.
•At present no methodology is available that can
be used to select the right design pattern at the
right point during a design exercise.
ANTIPATTERN
• If a pattern represents a best practice, then an
anti pattern represents lessons learned from a
bad design.
• An anti pattern describes a bad solution to a
problem that may deceptively appear to be
good solution, and how the use of the
deceptive and bad solution can be avoided.
• Anti patterns are valuable because they help
us to recognise why a particular design
alternative might seem at first like an attractive
solution, but later on lead to complicacies and
finally turn out to be a poor solution.
ANTIPATTERN
Input kludge:
• This concerns failing to specify and implement
a mechanism for handling invalid inputs.
Magic pushbutton:
• This concerns coding business logic directly
within the code of the user interface, rather
than performing them in separate classes.
Race hazard:
• This concerns failing to see the consequences
of all the different ordering of events that might
take place in practice.
SOME COMMON DESIGN
PATTERNS
• After you understand these patterns well, you
should be able to spot these patterns while
solving problems and then effortlessly use the
commonly accepted solutions captured by the
patterns.
• Also, a familiarity with the pattern terminologies
would help you to master the vocabulary
needed to discuss alternate pattern solutions
with your colleagues while working out design
solutions.
SOME COMMON DESIGN
PATTERNS
• For example, your colleague might while
reviewing your design suggest a way to
improve your design by saying
“Why not use MVC pattern in the part of your
design concerned with handling user
inputs?”
• It should be remembered that patterns offer
generic solutions that usually need to be fine
tuned in the context of specific problems.
SOME COMMON DESIGN
PATTERNS
• Though a large number of design patterns
have been proposed so far, the General
Responsibility Assignment Software
Patterns (GRASP) patterns by Larman [1998]
and gang of four or GoF (proposed by Erich
Gamma, Richard Helm, Ralph Johnson and
John Vlissides) patterns are extremely popular.
GRASP
• GRASP stands for General Responsibility
Assignment Software Patterns.
• The mnemonic meaning could be
“Successful OOAD requires Grasping”
• General: widely applicable for variety of situations
• Responsibility: information object performing duty
of holding information, computational object
performing duty of computation
• Assignment: Giving a responsibility to a module-
capability to carry out responsibility structure and
methods
• Software: Computer code
• Patterns: Regularities, templates, abstraction
GRASP
• Assigning responsibilities to objects is always
is major task in designing the software.
• Specifically it’s always a challenge to decide
which object carry out what responsibilities
and quality of software design largely
depended upon such responsibilities
assignment.
• Poor choices about such responsibilities
leads to fragile systems and components
which are hard to maintain, understand,
reuse or extend.
GRASP PATTERNS
• GRASP patterns describe fundamental
principles of assigning responsibilities to objects
and it has following principles and patterns in the
family
– Information
– Expert
– Creator
– Controller
– Low Coupling
– High Cohesion
– Polymorphism
– Pure Fabrication
– Indirection
– Protected Variations
EXPERT
PROBLEM ADDRESSED:
When a certain activity needs to be
performed, which class should be
assigned the responsibility for doing
it?
SOLUTION:
Assign responsibility to the information
expert i.e., the class that has all (or
most of) the information necessary to
fulfill the required responsibility.
EXPERT
• The expert pattern expresses the common
intuition that objects should do things
related to the information they store.
• As an example, the class and
collaboration diagrams for the solution to
the problem of which class should
compute the total cost of a sale
transaction
EXPERT-Example
EXPLANATION
• A sale transaction consists of many sale
items.
• Each saleItem object is associated with an
itemSpecification object.
• The itemSpecification object among other
things indicates the unit price for the item.
• In this situation, which object should
compute the total price for a sale
transaction?
EXPERT-Example
• Let us consider the different options that
are available.
• Should
– the saleTransaction object,
– the saleItem object, or
– the itemSpecification object
be given the responsibility to compute the
price of a sale transaction?
EXPERT-Example
• If we assign the responsibility to the
saleItem object to compute the transaction
price, then it would need several information
from the saleTransaction object such as the
number of items sold for various items and
could also need the prices for the other
items from the corresponding
itemSpecification objects for this
computation. This would require large data
exchanges among the objects to occur, and
lead to a poor quality solution.
EXPERT-Example
• Similarly, itemSpecification would be a poor
choice for computing the total cost payable for
a sale transaction, since the object lacks most
of the information required to compute the total
cost of the transaction.
• It can easily be seen that the saleTransaction
object has most of the information required for
the computation, and should be assigned the
responsibility to compute the total price. It is
the information expert, as far as the exact
items and quantities sold are concerned.
EXPERT-Example
• sale transaction solution
CREATOR
PROBLEM ADDRESSED:
Which class should be responsible
for creating a new instance of a
certain class?
CREATOR
SOLUTION:
Assign a class C1 the responsibility to create
an instance of class C2, if one or more of
the following are true:
• „ C1 is an aggregator of objects of type C2.
• „ C1 contains objects of type C2.
• „ C1 closely uses objects of type C2.
• „ C1 has the data that would be required to
initialise the objects of type C2, when they
are created.
CREATOR
EXPLANATION:
• An aggregator object needs to create all
its component objects, since the
aggregator needs to maintain the
addresses of its component objects.
• Any other object needing some
information from a component would have
to request the aggregator to retrieve the
information.
CREATOR
EXPLANATION:
• Occasionally, in an object-oriented
programming problem, an object may
need to be created which is not a part of
any aggregate object.
• In this case, the object should be created
by the one that has the required
initialization parameters, or the one that
would work most closely with the object.
CREATOR-EXAMPLE
POINT OF SALE(POS) SYSTEM
• we come across malls where there are
many POS counters.
CREATOR-EXAMPLE
POINT OF SALE(POS) SYSTEM
• A class “Register” represents the sales
register.This would have details of all sales
done.
• As the “Register” aggregates the “Sale”, it
fulfils the first criteria of the solution.
• Similarly the “Sale” contains the
“SaleLineItem”.
• Hence “Register” should create the
instance of “Sale” and “Sale” should create
instance of “SaleLineItem”.
CREATOR-EXAMPLE
FACADE
PROBLEM ADDRESSED:
How should the services be requested
from a service package by client
classes (i.e., classes outside the
package)?
SOLUTION:
A separate class (such as DBfacade)
should be created to provide a
common
interface to the services provided by the
FACADE
EXAMPLE:
• In Java, the interface JDBC can be called
a facade because, we as users or clients
create connection using the
“java.sql.Connection” interface, the
implementation of which we are not
concerned about. The implementation is
left to the vendor of driver.
FACADE
EXAMPLE:
• When a computer starts up, it involves the
work of CPU, memory, hard drive, etc. To
make it easy to use for users, we can add
a facade which wrap the complexity of the
task, and provide one simple interface
instead.
FACADE
EXAMPLE:
Consider a lecture hall complex.
• Suppose all students are required to
enter the lecture hall complex through the
main entrance only.
• In this case, when some general
information such as cancellation of some
lectures on a certain dates is to be
brought to the notice of all the students,
displaying one notice at the entrance
should be enough.
FACADE
EXAMPLE:
• But, consider the situation where the
students enter the lecture hall complex
through multiple entrances, and are even
allowed to jump into the class rooms
through the different windows of various
class rooms.
• In this case, notices have to be displayed
at all possible points of entry of the
students.
FACADE
FACADE
EXPLANATION:
• In the context of a service package,
when (the type or number of) the
parameters of some method of a class in
the package changes, all classes that
invoke the method have to be changed.
• However, when outside objects (clients)
invoke services through a facade class,
the change can be absorbed in the
facade class and changes to the client
classes can be avoided.
FACADE
EXPLANATION:
• Also, use of a facade class reduces the
complexity of service invocation, since
client classes need not be aware of the
specific classes that implement the
services.
MODEL VIEW SEPERATION
PATTERNS
PROBLEM ADDRESSED:
How should the non-GUI classes
communicate with the GUI classes and
vice versa?
Context in which the problem occurs:
Here, view is a synonym for the presentation layer
objects (or GUI objects), and model is a synonym
for the domain layer (non-GUI) objects. The domain
layer objects are responsible for actually providing
the required service, whereas the presentation
layer objects are responsible for handling only the
interactions (input/output) with the user.
MODEL VIEW SEPERATION
PATTERNS
SOLUTION:
Depending on the context, the is solution
provided by either of the 3 patterns can
be used.
Observer Pattern,
Model-View-Controller (MVC) pattern
Publish-Subscribe Pattern
MODEL VIEW SEPERATION
PATTERNS
EXPLANATION:
•Whenever any interaction between a
model object and a view object is required,
the model object should be loosely
coupled to the view objects.
• Also, the view objects normally undergo
changes much more frequently as
compared to the model objects.
• Each change to a view object should not
require changes to be made to the model
objects.
MODEL VIEW SEPERATION
PATTERNS
EXPLANATION:
• When information is required to be
displayed synchronously, above solution is
satisfactory.
• That is, the view object simply get the
required information from the model object
through a method call.
• However, this solution does not work
satisfactorily for asynchronous information
display.
MODEL VIEW SEPERATION
PATTERNS
• The context of the problem here is that,
the view object should display
information with the model each time the
state of the model changes.
• But, the view does not display when the
state of the model object would change.
• Therefore, the view object would not
know when to make the method call.
MODEL VIEW SEPERATION
PATTERNS
• When information is produced
asynchronously by a model object, the
view object would not know when exactly
new information would be available so that
request for it can be made.
• Also, polling (periodically requesting
information to check if new information
has become available) is not a satisfactory
solution on efficiency considerations.
MODEL VIEW SEPERATION
PATTERNS
• Consider a software that monitors the
stock market quotations continuously and
alerts the user whenever the required
stock quotations reach some pre-
specified threshold value.
• This software would pop-up an alert
message as soon as any of the stock
quotation reaches its threshold value.
• In this case, the alert message pops up
asynchronously.
MODEL VIEW SEPERATION
PATTERNS
• Consider a software that monitors the
stock market quotations continuously and
alerts the user whenever the required
stock quotations reach some pre-
specified threshold value.
• This software would pop-up an alert
message as soon as any of the stock
quotation reaches its threshold value.
• In this case, the alert message pops up
asynchronously.
MODEL VIEW SEPERATION
PATTERNS
• The main idea behind the model-view
separation pattern is to achieve loose
coupling between the model and view
objects, so that the complexity of design
is reduced and reuse of the model
objects is enhanced.
• There are several variations of model-
view separation pattern that are useful in
different situations of interaction between
the model and the view objects.
OBSERVER
PROBLEM ADDRESSED
• When a model object is accessed by
several view objects, how should the
interactions between the model and
the view objects be structured?
OBSERVER
SOLUTION
• Observers should register themselves with
the model object.
• The model object would maintain a list of
the registered observers.
• When a change occurs to the model object,
it would notify all the registered observers.
• Each observer can then query the model
object to get any specific information about
the changes that it might require.
OBSERVER
• The interaction diagram for this pattern
is shown in Figure
OBSERVER
EXPLANATION:
• The observer pattern solution achieves
loose coupling between the model and
observer objects.
• Also, it achieves decoupling among the
observers themselves, they need not be
aware of each other.
• Once an observer has been informed of
a change, it may query the model for
some specific piece of information.
OBSERVER
LIMITATIONS:
The observer pattern has the following
limitations:
• „The model objects incur a substantial
overhead to support registration of the
observers, and also to respond to the
queries from the observers. This is
detrimental to performance of the model
objects, especially when the number of
observers is large.
OBSERVER
LIMITATIONS:
• The two-stage process (notification and
query) reduces coupling between the
model and observer objects. However,
selective notification to only the
interested observers would make this
solution very inefficient, since
unnecessary message exchanges may
occur when different observers are
interested in different types of events.
MODEL VIEW
CONTROLLER - MVC
PROBLEM ADDRESSED:
How should the GUI objects
interact with the model object?
MODEL VIEW
CONTROLLER - MVC
SOLUTION:
The GUI objects need to be separated
into view and controller types. The
controller objects are responsible for
collecting the data input by a user.
The controller would pass the
collected information onto the model
object. The model object would notify
the view and controller objects
regarding any changes to its state as
and when it occurs.
MODEL VIEW
CONTROLLER - MVC
The class and collaboration diagrams for
the MVC pattern have been shown in
figures
MODEL VIEW
CONTROLLER - MVC
EXPLANATION:
• When a controller object collects
input data and passes those onto a
model object, the state of the model
object may change.
• When the state of the model
changes, it can send an update
message to all dependent view and
controller objects.
MODEL VIEW
CONTROLLER - MVC
EXPLANATION:
• The purpose of the model object
notifying the view object is obvious (that
is, to refresh the display with the updated
information).
• The controller object also needs to be
notified, since the new model object
state may need dimming certain menu
options, or even closing certain control
objects.
MODEL VIEW
CONTROLLER - MVC
BENEFITS:
• Benefits of this pattern include loose
coupling between the view and
model objects.
• A clear separation between the code
that handles inputs, that displays
data, and that processes the
application’s data.
MODEL VIEW
CONTROLLER - MVC
• This is useful in situations where multiple
views of the same data needs to be
presented.
• In particular, this pattern is useful in
applications in which the model object
can change its state asynchronously and
multiple consistent views of the model
object need to be displayed effectively.
MODEL VIEW
CONTROLLER - MVC
• As a simple example, the MVC pattern
can be used when for the same input
data needs to be displayed in several
different representations such as line
plot, bar chart, and pie chart.
• In this case, whenever the model
changes its data or properties, all
dependent views are automatically
updated.
DESIGN PATTERNS IN
SMALLTALK MVC
• The Model/View/Controller (MVC) triad of
classes is used to build user interfaces in
Smalltalk-80.
• MVC consists of three kinds of objects.
– The Model is the application object,
– The View is its screen presentation,
– The Controller defines the way the user
interface reacts to user input.
DESIGN PATTERNS IN
SMALLTALK MVC
• Before MVC, user interface designs
tended to lump these objects together.
• MVC decouples them to increase flexibility
and reuse.
• MVC decouples views and models by
establishing a subscribe/notify protocol
between them.
DESIGN PATTERNS IN
SMALLTALK MVC
• A view must ensure that its appearance
reflects the state of the model.
• Whenever the model's data changes, the
model notifies views that depend on it.
DESIGN PATTERNS IN
SMALLTALK MVC
• In response, each view gets an
opportunity to update itself.
• This approach lets you attach multiple
views to a model to provide different
presentation.
• You can also create new views for a
model without re-writing it.
PUBLISH-SUBSCRIBE
• The publish-subscribe pattern is a more general
form of the observer pattern and overcomes many
of the shortcomings of the observer pattern.
PROBLEM ADDRESSED:
When a set of model objects are
accessed by a large number of view
objects, and the model states
change asynchronously, how
should the interaction be
structured?
PUBLISH-SUBSCRIBE
SOLUTION:
• This pattern suggests that an event
notification system should be
implemented through which the publisher
(model objects) can indirectly notify the
subscribers as soon as the necessary
information becomes available.
• An event manager class can be defined
which keeps track of the subscribers and
the types of events they are interested in.
PUBLISH-SUBSCRIBE
SOLUTION:
• An event is published by the publisher by
sending a message to the event
manager object.
• The event manager notifies all registered
subscribers usually via a parameterised
message (called a callback )
PUBLISH-SUBSCRIBE
PUBLISH-SUBSCRIBE
• The publish-subscribe pattern has been
schematically shown in the figure.
• Observe that the GUI objects have
subscribed to the event e1 with the
corresponding event manager.
• As soon as a model object publishes the
event e1, the corresponding event
manager would notify (callback) the GUI
objects that have subscribed to the
event.
PUBLISH-SUBSCRIBE
EXPLANATION:
• The publish-subscribe pattern requires
creating an event manager class for each
type of event that the model objects may
generate.
• A subscriber may register its interest for a
class of events by subscribing to the
corresponding event manager classes.
• Events generated by publishers are
selectively notified to the appropriate event
managers,who in turn notify the subscribers.
PUBLISH-SUBSCRIBE
EXPLANATION:
• The selection is achieved by defining
event manager classes.
• As soon as an event occurs, the event
manager passes the information to all
those who ha
• For example, when a publisher
generates an event e1, the
corresponding event manager is notified
of the same.ve subscribed to the event.
PUBLISH-SUBSCRIBE
EXPLANATION:
• All subscribers that previously
subscribed to the event e1 would
receive an asynchronous notification of
the occurrence of e1.
• The subscriber may respond to the
event by associating a specific handler
with each class of events.
PUBLISH-SUBSCRIBE
EXPLANATION:
• The event manager is responsible for
registering subscriptions, receiving events
from models, filtering events, and passing
them to the interested subscribers.
• Depending on the specific system, the
event manager may be implemented in
various ways, e.g., by a centralised server,
by distributed co-operating servers, or
possibly collectively by the publishers.
PUBLISH-SUBSCRIBE
PUBLISH-SUBSCRIBE
EXPLANATION:
• Compared to the observer pattern, this pattern
frees the model object from handling the
registration of observer objects and notification
objects.
• Thus, this pattern has obvious advantage over
the observer pattern, especially when the
number of observers is large.
• Modern object-oriented languages support
several event manager classes.
• For example, Java provides the EventListener
interface for such purposes.
PROXY OR INTERMEDIARY
PROBLEM ADDRESSED:
How should a client object invoke
the services of a server object?