0% found this document useful (0 votes)
19 views

Umldp Unit IV

Uploaded by

harshadnani2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Umldp Unit IV

Uploaded by

harshadnani2004
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

UML & Design Patterns 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.

What is a Design pattern?


Design pattern is a general reusable solution to a commonly occurring problem in software
design. The patterns typically show relationships and interactions between classes or
objects. The idea is to speed up the development process by providing tested, proven
development paradigm.

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.

What is Gang of Four (GoF)?


In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John
Vlissidespublished a book titled Design Patterns - Elements of Reusable Object-
Oriented Software which initiated the concept of Design Pattern in Software
development.These authors are collectively known as Gang of Four (GOF).

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

Types of Design Patterns


There are mainly three types of design patterns:
1. Creational patterns: These design patterns are all about class instantiation or
object creation.
2. Structural patterns :These design patterns are about organizing different classes
and objects to form larger structures and provide new functionality
3. Behavioral patterns: These patterns are most specifically concerned with
communication between objects.

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

3. Factory Method 3. Composite. 3. Interpreter


4. Decorator 4. Iterator
4. Prototype
5. Facade 5. Mediator
5. Singleton
6. Flyweight 6. Memento
7. Proxy 7. Observer
8. State
9. Strategy
10. Template
11. Visitor

Describing Design Patterns


A design patterns can be described using a consistent format. It contains:
 Pattern Name and Classification: It conveys the essence of the pattern
succinctly good name is vital, because it will become part of design vocabulary.
 Intent: What does the design pattern do?
o What is it’s rational and intend?
o What particular design issue or problem does it address?
 Also Known As: Other well-known names for the pattern, if any.
 Motivation: A scenario that illustrates a design problem and how the class and
object structures in the pattern solve the problem.The scenario will help
understand the more abstract description of the pattern that follows.
 Applicability
o What are the situations in which the design patterns can be applied?
o What are examples of the poor designs that the pattern can address?
o How can recognize situations?
 Structure: Graphical representation of the classes in the pattern using a notation
based on the object Modeling Technique(OMT).
 Participants: The classes and/or objects participating in the design pattern and
their responsibilities.
 Collaborations: How the participants collaborate to carry out their responsibilities.
 Consequences
o How does the pattern support its objectives?
o What are the trade-offs and result of using the pattern ?

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?

Singleton pattern (Creational)


Intent
Ensure a class only has one instance, and provide a global point of access to it.

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.

Implementation of singleton pattern in Temple Run2

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.

Also Known As VirtualConstructor.

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

class 350Z implements Car; // fast car


classCargo implements Car; // truck
class Accord implements Car; // family car
public class carFactory{
public static Car create(String type) {
if (type.equals("fast"))
return new 350Z();
elseif (type.equals("truck"))
return new Ram();
else if (type.equals(“family”)
return new Accord();
}
}

6
UML & Design Patterns UNIT-IV
Car fast = carFactory.create("fast"); // returns fast car
Related Patterns
− Abstract Factory
− Template Method
− Prototype

Facade pattern (Structural)


Intent
Provide a unified interface to a set of interfaces in a subsystem. Façade defines a
higher-level interface that makes the subsystem easier to use. Wrap a complicated
subsystem with a simpler interface.

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.

Non-software example for Façade


The customer service representative acts as a Facade, providing an interface to the order
fulfillment department, the billing department, and the shipping department.

Fig. Object Diagram for facade using Phone Order

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

Observer / Publish-Subscribe Pattern (Behavioral)


Intent
Define a one-to-many dependency between objects where a state change in one object
results in all its dependents being notified and updated automatically.

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.

− Object that changes called “Subject”.


− Object that receives updates called “Object”.

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

Pure Fabrication Pattern (GRASP)


Problem
How to assign responsibilities if applying the Informational Expert principle decreases
cohesion and increases coupling?

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.

In general, “Assign the responsibilities to an intermediate object which in turn collaborates


with two objects avoiding the directly coupling i.e. indirection”.

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.

− The solution is to create a new class say “PersistentStorageBroker” 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 fashion the “PersistentStorageBroker” is also highly cohesive by performing


the sole responsibility of saving the instance / object.
Discussion
− Many problems in computer science can be solved by another level of indirection.
− Pure Fabrications are generated because of indirection.

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

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy