Umldp Unit IV
Umldp Unit IV
Introduction
Design patterns are used to represent some of the best practices adapted by experienced
object-oriented software developers.
A design pattern systematically names, motivates, and explains a general design that
addresses a recurring design problem in object-oriented systems.
It describes the problem, the solution, when to apply the solution, and its consequences. It
also gives implementation hints and examples.
Goals
Understand the problem and matching it with some pattern
Re-usage of old interface or making the present design reusable for the future
usage.
According to these authors design patterns are primarily based on the following principles
of object orientated design.
Program to an interface not an implementation
Favor object composition over inheritance
1
UML & Design Patterns UNIT-IV
List of Design Patterns
Creational Patterns Structural Patterns Behavioral patterns
1. Abstract Factory 1. Adapter: 1. Chain of Responsibility
2. Builder 2. Bridge. 2. Command
2
UML & Design Patterns UNIT-IV
o What aspect of the system structure does it let vary independently?
Implementation
o What pitfalls, hints,or techniques should be aware of when implementing
the pattern ?
o Are there language-specific issues?
Sample Code: Code fragments that illustrate how might implement the pattern in
C++ or Smalltalk.
Known Uses: Examples of the pattern found in real systems.
Related Patterns:
o What design patterns are closely related to this one?
o What are the important differences?
o With Which other patterns should this one be used?
Motivation
Some classes should have exactly one instance(one print spooler, one file system,
one window manager).
A global variable makes an object accessible, but it doesn’t keep you from
instantiating multiple objects.
Class itself responsible for keeping track of its sole instance.
Applicability
Use the Singleton pattern when
There must be exactly one instance of a class, and it must be accessible to clients
from a well-known access point.
The sole instance should be extensible by subclassing, and clients should be able
to use an extended instance without modifying their code.
Structure
3
UML & Design Patterns UNIT-IV
Participants
Singleton
Defines an instance operation that lets clients access its unique instance.
Instance is a class operation (static in Java).
May be responsible for creating its own unique instance.
Collaborations
Clients access a Singleton instance solely through Singleton’s Instance operation.
Consequences
The Singleton pattern has several benefits:
Controlled access to sole instance.
Reduced name space.
Permits refinement of operations and representation.
Permits a variable number of instances.
More flexible than class operations
Example
Non-software example
The office of the President of the United States is a Singleton. The United States
Constitution specifies the means by which a president is elected, limits the term of office,
and defines the order of succession. As a result, there can be at most one active president
at any given time. Regardless of the personal identity of the active president, the title, "The
President of the United States" is a global point of access that identifies the person in the
office.
Software example
In temple run game, the player can play well and set high score. This high score is a single
instance of a class. It is a global point of access that identifies highest scored points.
4
UML & Design Patterns UNIT-IV
Factory Method Pattern (Creational)
Intent
Define an interface for creating an object, but let subclasses decide which class to
instantiate.Factory Method lets a class defer instantiation to subclasses.
Motivation
Factory Method is used in frameworks where library code needs to create objects of types
which may be sub classed by applications using the framework.Since the library knows
when an object needs to be created, but not what kind of object it should create, this being
specific to the application, it can use the Factory Method.
Applicability
Use the Factory Method pattern when:
− A class can’t anticipate the types of objects it must create.
− A class wants its subclasses to specify the object to create.
− The designer wants to localize knowledge of helper sub classes.
Structure
Participants
1. Product (Document)
5
UML & Design Patterns UNIT-IV
− Defines the interface of objects the factory method creates
2. ConcreteProduct (MyDocument)
− Implements the product interface
3. Creator (Application)
− May contain a default implementation of the factory method.
− Declares the factory method which returns object of type product.
− Creator relies on its subclasses to define the factory method so that it returns
an instance of the appropriate Concrete Product.
4. ConcreteCreator (MyApplication)
− Overrides factory method to return instance of ConcreteProduct
Collaborators
− The Creator relies on the subclass’s factory method to return an instance of
appropriate ConcreteProduct object.
Example
Car Factory produces different Car objects
Original
− Different classes implement Car interface
− Directly instantiate car objects
− Need to modify client to change cars
Using pattern
− Use carFactory class to produce car objects
− Can change cars by changing carFactory
6
UML & Design Patterns UNIT-IV
Car fast = carFactory.create("fast"); // returns fast car
Related Patterns
− Abstract Factory
− Template Method
− Prototype
Motivation
− Structuring a system into subsystems helps reduce complexity.
− A common design goal is to minimize the communication and dependencies
between subsystems. One way to achieve this goal is to introduce a facade object
that provides a single, simplified interface to the more general facilities of a
subsystem.
Applicability
Use the Façade pattern when:
− You want to provide a simple interface to a complex subsystem.
− There are many dependencies between clients and the implementation classes of
an abstraction.
− You want to layer your subsystems.
Structure
7
UML & Design Patterns UNIT-IV
Participants
Façade
− Delegate requests to appropriate subsystem objects.
Subsystem classes
− Implement subsystem functionality.
− Handle work assigned by the facade.
Collaborators
Facade forwards the clients’ requests to the appropriate subsystem objects.
Subsystem objects perform the actual work.
Façade may add some functionality of its own.
Consequences
It offers the following benefits:
− It shields clients from subsystem components.
− It promotes weak coupling between the subsystem and its clients.
− Reduce compilation dependencies.
− It doesn’t prevent applications from using subsystem classes
Implementation
Consider the following issues when implementing a facade:
− Reducing client-subsystem coupling.
− Public versus private subsystem classes.
Software example
In temple run game the “upgrade” option acts as a facade, giving an interface for selecting
a player, for abilities and power-ups.
8
UML & Design Patterns UNIT-IV
Implementation of facade pattern in Temple Run2
Related Patterns
− Adapter
− Abstract Factory
− Mediator
− Singleton
Also Known As
− Publish-Subscribe
− Dependents,
Motivation
Partitioning a system into a collection of cooperating classes is the need to maintain
consistency between related objects.
9
UML & Design Patterns UNIT-IV
Applicability
Use the Observer pattern in any of the following situations:
− When an abstraction has two aspects,
o One dependent on the other.
o Encapsulating these aspects in separate objects lets you vary and reus
them independently.
− When a change to one object requires changing others whose identity is not
necessarily known.
Structure
Participants
Subject
− Has a list of observers.
− Interfaces for attaching/detaching an observer
Observer
− An updating interface for objects that gets notified of changes in a subject.
ConcreteSubject
− Stores state of interest to observers
− Sends notification when state changes.
ConcreteObserver
− Implements updating interface.
Collaborations
ConcreteSubject notifies its observers whenever a change occurs that could make its
observers' state inconsistent with its own. The following interaction diagram illustrates the
collaborations between a subject and two observers:
10
UML & Design Patterns UNIT-IV
Consequences
− Abstract coupling between subject and observer. (subject need not know concrete
observers)
− Support for broadcast communication (all observers are notified)
− Unexpected updates (observers need not know when updates occur)
Implementation
interface Observer
{
void update (Observable sub, Object arg)
}
class Observable {
public void addObserver(Observer o) { }
public void deleteObserver (Observer o){ }
public void notifyObservers(Object arg){ }
public boolean hasChanged(){ }
}
public PiChartView implements Observer {
void update(Observable sub, Object arg) {
// repaint the pi-chart
}
}
class StatsTable extends Observable{
public boolean hasChanged() {
// override to decide when it is considered changed
}
11
UML & Design Patterns UNIT-IV
Example
In temple run game, when the player completes certain objective(s) following needs to be
updated/notified automatically:
− Current list(list of objectives to be achieved)
− Complete list(list of objectives completed)
− Increase multiplier
− Increase score
Implementation of observer pattern in Temple Run2
Related Patterns
− Mediator
− Singleton
Solution
− Assign the responsibility to an artificial class that does not belong to the domain
model.
− Pure Fabrication is a class that does not reflect any business domain object, but
required only for increase cohesion and decrease coupling.
Example
In NEXTGen POS: Who takes the responsibility of saving the instance of “Sale”?
Design- I
12
UML & Design Patterns UNIT-IV
− This results in large number of database oriented operations which actually has
nothing to do with “Sales”. Also there could be additional overhead of transaction
related stuff.
− This leads the “Sale” class towards the low cohesion.
Design-II
The solution is to create a new class say “StorageAgent“ which would interact with
database interface and saves the instance of “Sale” class.
As “Sale” would be spared from saving its own instance into database thus giving
rise to high cohesion and low coupling.
In this “StorageAgent” is also highly cohesive by performing the sole
responsibility of saving the instance / object.
Discussion
There are 2 approaches of designing which the pure fabrication is the behavioral way:
− Representation decomposition: Designing the objects the way they represent in
the domain.
− Behavioral decomposition: Designing the objects the way they do. These are
function centric or encapsulate algorithm.
Commonly, the pure fabrication is used to place / encapsulate the algorithm or function
which doesn’t fit well in other classes.
Contradictions
Sometimes such design may result into bunch of classes having a single method which
is a kind of overkill.
Benefits
− Supports Low Coupling
− Results in high cohesion
− Promotes reusability
13
UML & Design Patterns UNIT-IV
Related Patterns
− Low Coupling
− High Cohesion
− A Pure Fabrication usually takes on responsibilities from domain class that would
be assigned those responsibilities based on Expert pattern
Indirection / Indirect Fabrication Pattern (GRASP)
Problem
− Where to assign a responsibility, to avoid direct coupling between two (or more)
things?
− How to de-couple objects so that low coupling is supported and reuse potential
remains higher?
Solution
Assign responsibility to intermediate class for providing linking between objects not linking
directly. The intermediary creates an indirection between the other components.
Approach
Step I: Closely look at domain/ design model and locate the classes with low coupling or
direct coupling
Step II: Use an existing class to take the responsibility of functionality causing low
coupling and also the functionality has high potential for reuse.
Example: The example for “Pure Fabrication” is valid for indirection too.
14
UML & Design Patterns UNIT-IV
− The large number of database operations, are generally common for different
domain objects which motivates to assign the responsibility of database operations
to an intermediate object decoupling the database and domain objects. This would
result in very general classes which can be used by many objects.
− As “Sale” would be spared from saving its own instance into database thus giving
rise to high cohesion and low coupling.
Contraindictions
− Sometimes such design may result into bunch of classes having a single method
which is a kind of overkill.
Benefits
− Lower coupling betwee components
− Results in high reusability
Related Patterns
− Low Coupling
− Protected Variations
− Many Indirection intermediaries are Pure Fabrications
− Many GoF Patterns such as Adapter, Façade, Observer and Mediator
15