0% found this document useful (0 votes)
40 views37 pages

OOAD - Unit 4

The document discusses GRASP (General Responsibility Assignment Software Patterns), which provides principles for assigning responsibilities in object-oriented design. It outlines nine key patterns, including Information Expert, Creator, and Controller, emphasizing the importance of low coupling and high cohesion in software design. The document also explains how these principles can be applied in practical scenarios, such as a Point of Sale application, to enhance maintainability and reusability of code.
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)
40 views37 pages

OOAD - Unit 4

The document discusses GRASP (General Responsibility Assignment Software Patterns), which provides principles for assigning responsibilities in object-oriented design. It outlines nine key patterns, including Information Expert, Creator, and Controller, emphasizing the importance of low coupling and high cohesion in software design. The document also explains how these principles can be applied in practical scenarios, such as a Point of Sale application, to enhance maintainability and reusability of code.
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/ 37

CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

UNIT IV DESIGN PATTERNS

GRASP

GRASP is the abbreviation of General Responsibility Assignment Software Patterns (or


Principles). It consists of guidelines for assigning responsibility to classes and objects in
object-oriented design.
The different patterns and principles used in GRASP are:

1. Information Expert,
2. Creator,
3. Controller,
4. Low Coupling,
5. High Cohesion,
6. Polymorphism,
7. Pure Fabrication,
8. Indirection,
9. Protected Variations.

All these patterns answer some software problem, and in almost every case these problems
are common to almost every software development project. These techniques have not been
invented to create new ways of working but to better document and standardize old, tried-
and-tested programming principles in object oriented design.
It has been said that "the critical design tool for software development is a mind well
educated in design principles. It is not the UML or any other technology". Thus, GRASP is
really a mental toolset, a learning aid to help in the design of object oriented software.

Department of IT, Sri Sai Ram Engineering College Page 1


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

The GRASP pattern is summarized as given below:

1. Information Expert – A general principles of object design and responsibility


assignment.
2. Creator – Who creates the classes?
3. Controller – Which first object beyond the UI layer receives and coordinates a
system operation?
4. Low Coupling – How to reduce the impact of change?
5. High Cohesion – How to keep objects focused, understandable and manageable?
6. Polymorphism – Who is responsible when behaviour varies by type?
7. Pure Fabrication – Who is responsible when the designer and system developer do
not want to violate high cohesion and Low coupling?
8. Indirection – How to assign responsibilities to various classes in order to avoid direct
coupling?
9. Protected Variations – How to assign responsibilities so that the variations in the
elements that do not have an undesirable impact on other elements?

Designing objects with responsibilities:


Responsibilities and Methods:
Responsibility is defined as a contact or obligation of a class. Responsibilities of a class
reflect the behaviour of the objects which are grouped into classes.
The two types of responsibilities are:

1. Knowing
2. Doing

Knowing Responsibilities of an object deals with the following:

 Knowing about private encapsulated data


 Knowing about related objects
 Knowing about things it can be derive or calculate
Doing Responsibilities of an object deals with the following:
 Doing something itself such as creating an object
 Doing a calculation
 Initiating action in other objects

Patterns of the GRASP:


Creator:

Creator is a GRASP Pattern which helps to decide which class should be responsible for
creating a new instance of a class. Object creation is an important process, and it is useful to
have a principle in deciding who should create an instance of a class.
Problem - Who should be responsible for creating a new instance of some class?

Department of IT, Sri Sai Ram Engineering College Page 2


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Solution - Creation of objects is one of the most common activities in an object-oriented


system. Which class is responsible for creating objects is a fundamental property of the
relationship between objects of particular classes.
In general, a class B should be responsible for creating instances of class A if one, or
preferably more, of the following apply:

 Instances of B contain or compositely aggregate instances of A


 Instances of B record instances of A
 Instances of B closely use instances of A
 Instances of B have the initializing information for instances of A and pass it on
creation

Example:

Let's consider Point of Sale (POS) application: Here is a brief overview of


the POS application.

 POS application for a shop, restaurant, etc. that registers sales.


 Each sale is of one or more items of one or more product types and happens at a
certain date.
 A product has a specification including a description, unitary price, an identifier.
 The application also registers payments (say, in cash) associated with sales.
 Payment is for a certain amount, equal to or greater than the total of the sale.

Problem - Who should be responsible for creating a SalesLineltem instance?

Solution - By Creator, we should look for a class that aggregates, contains, and so
on, SalesLineltem instances.

From the above class diagram, The Sale class contains (in fact, aggregates)
many SalesLineltem objects, the Creator pattern suggests that Sale class is a good candidate
to have the responsibility of creating SalesLineltem instances.
Department of IT, Sri Sai Ram Engineering College Page 3
CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Benefits

• Lower maintenance due to low coupling


• Higher opportunities for reuse

Information expert
Information expert (also expert or the expert principle) is a principle used to
determine where to delegate responsibilities such as methods, computed fields, and so on.
Using the principle of Information Expert a general approach to assigning responsibilities is
to look at a given responsibility, determine the information needed to fulfill it, and then
determine where that information is stored. Information Expert will lead to placing the
responsibility on the class with the most information required to fulfill it.
Problem - What is a general principle of assigning responsibilities to objects?
Solution - Assign responsibility to the information expert - the class that has the information
necessary to fulfill the responsibility.
Example:
Let's consider Point of Sale (POS) application: a brief overview of the POS application.

 Application for a shop, restaurant, etc. that registers sales.


 Each sale is of one or more items of one or more product types and happens at a
certain date.
 A product has a specification including a description, unitary price, an identifier.
 The application also registers payments (say, in cash) associated with sales.
 Payment is for a certain amount, equal to or greater than the total of the sale.

Problem statement: Who's responsible for knowing the grand total of a Sale?

Department of IT, Sri Sai Ram Engineering College Page 4


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

To determine lineitem sub total we need,


SalesLineitem.quantity
ProductDescription.price
By information expert using the above the SalesLineItem should determine subtotal.
This is done by
 Sale sending getSubtotal messages to each SalesLineItem and sum the results.

After knowing and answering subtotal, a SalesLineItem has to know product price.
ProductDescription is an information expert for answering price.

• Thus information expert is used in the assignment of responsibilities.


• Experts express the common ‗intuition‘ that objects do things related to information
they have.
• ‗Partial‘ information experts will collaborate in the task.
Example: Sales total problem – collaboration of three classes of objects.
Profit and loss statement – collaboration of chief financial officer, accountants to
generate reports on credits and debits.
• Information expert thus has real world analogy
• Information experts are basic guiding principle used continuously in object design.

Department of IT, Sri Sai Ram Engineering College Page 5


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Benefits
1) Information encapsulation use their information to fulfil tasks.
2) High cohesion is supported

Low Coupling
Coupling is a measure of how strongly one element is connected to, has knowledge of, or
relies on other elements. Low coupling is an evaluative pattern that dictates how to assign
responsibilities to support

 lower dependency between the classes


 change in one class having a lower impact on other classes
 higher reuse potential

Problem - How to support low dependency, low change impact, and increase reuse?
Solution - Assign a responsibility so that coupling remains low.

A class, for example, with high (or strong) coupling relies on many other classes. Such
classes may be undesirable; some suffer from the following problems:

 Forced local changes because of changes in related classes.


 Harder to understand in isolation.
 Harder to reuse because its use requires the additional presence of the classes on
which it is dependent.

Types of Coupling:

 Content coupling - modules rely on each others’ internal data or internal


organization
 Common coupling - modules share the same global data
 External coupling - modules share an externally imposed data format,
communication protocol or device interface
 Control coupling - one module controls the flow of another, such as by passing it a
flag or other information
 Stamp coupling - modules share a composite data structure but use different parts
of it
 Data coupling - modules share data through parameters, such as in a subroutine
call
 Message coupling - modules communicate by passing messages

Example

NextGen Case study

We have to create payment instance and associate it with sale.

Department of IT, Sri Sai Ram Engineering College Page 6


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Design 1:

Suggested by creator
1) Register instance send addpayment message to sale, passing newPayment
as a parameter.
2) Register class couples with payment class and creates payment.

Register creates Payment


Design 2:

Suggested by low coupling


1) Here sale does the creation of payment.
2) It does not increase coupling and hence preferred.

Sales creates Payment


Low coupling is an evaluation principle for evaluating all designs.
Common forms of coupling from objects A to B include
1) A has an attribute referring to B or instance of B
2) A calls B‘s services
3) A has a method referring to B or B‘s instance
4) A is direct/indirect subclass of B
5) B is an interface and A implements B.
Low coupling
1. Assigns responsibility that will not yield negative results that cause high coupling.
2. Support design of independent classes.
Classes that are
1) Generic in nature
2) Having high probability of reuse will have low coupling. Extreme case of
low coupling is no coupling between classes.

Department of IT, Sri Sai Ram Engineering College Page 7


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

That is not desired because a moderate degree of coupling between the classes is normal and
is necessary for creating an object oriented system.
High coupling to stable elements is seldom a problem.

Benefits • Not affected by changes in other components


• Simple to understand in isolation
• Convenient to reuse

High Cohesion

High cohesion is an evaluative pattern that attempts to keep objects appropriately focused,
manageable and understandable. High cohesion is generally used in support of low coupling.
The term cohesion is used to indicate the degree to which a class has a single, well-focused
responsibility. Cohesion is a measure of how the methods of a class or a module are
meaningfully and strongly related and how focused they are in providing a well-defined
purpose to the system.
Problem - How to keep classes focused, understandable and manageable?
Solution - Assign responsibilities so that cohesion remains high. Try to avoid classes to do
too much different things.
Example
Create a payment instance and associate it with sale

Design 1

• Register records a payment in real world


• Then it sends addpayment message to sale, passing newpayment as a parameter.

Register creates payment

Department of IT, Sri Sai Ram Engineering College Page 8


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Sale creates payment

• In the second design, payment creation in the responsibility of sale.


• It is highly desirable because it supports
◦ High cohesion and
◦ Low coupling
Scenarios of varying degrees of functional cohesion

(1) Very low cohesion


A class is solely responsible for many things in different functional areas.

(2) Low cohesion


A class has sole responsibility for a complex task in one functional area.

(3) High cohesion


A class has moderate responsibilities in one functional area and collaborates with
others.

(4) Moderate cohesion


A class has light weight. It is responsible for different areas logically related to the
class concept but not to each other.

Rule of thumb

A class with high cohesion has small number of methods (with highly related
functionality) and does not work too much.

High cohesion is
• Easy to maintain
• Understand and
• Reuse

Modular design

―Modularity is the property of system that has been decomposed into a set of
cohesive and loosely coupled modulesǁ.

Department of IT, Sri Sai Ram Engineering College Page 9


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Modular design creates methods and classes with single purpose, clarity and high
cohesion.

Benefits
1) Clarity
2) Ease of comprehension
3) Reuse of fine-grained, highly related functionality.

Controller:
The Controller is responsible for handling the requests of actors. The Controller is the
middle-man between your user clicking “Send” and your back-end making that happen.
Problem:
Who should be responsible for handling an input system event? An input system event is an
event generated by an external actor. They are associated with system operations of the
system in response to system events, just as messages and methods are related.
For example, when a writer using a word processor presses the "spell check" button, he is
generating a system event indicating "perform a spell check."
A Controller is a non-user interface object responsible for receiving or handling a system
event. A Controller defines the method for the system operation.
Who should be responsible for handling an input event, which object/s beyond the UI layer
receives interaction?
Solution:
Assign the responsibility for receiving or handling a system event message to a class
representing one of the following choices:

 Represents the overall system, device, or subsystem (facade controller).


 Represents a use case scenario within which the system event occurs, often named
Handler, Coordinator, or Session (use-case or session controller).
 Use the same controller class for all system events in the same use case scenario.

Example:
1) A cashier is POS terminal pressing ―EndSaleǁ button indicating ―sale has endedǁ
2) Writer using word processor presses ―spell checkǁ button to
perform checking ofspelling
Solution

Assign responsibility to one of the following


• Represents overall ―systemǁ, ―a root objectǁ
◦ These are variations of façade controller.
• Represents a usecase scenario called

Department of IT, Sri Sai Ram Engineering College Page 10


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN
◦ <usecaseName> handler
◦ <usecaseName> coordinator or
◦ <usecaseName> session
Here we use some controller class for all system events in same usecase scenario.
A session is an instance of a conversation with an actor.
Example:
NextGen application contains several system operations.

Some system operations of NextGen POS Application


During the design the responsibility of system operations is done by the controller.

Controller for enterItem

The controller are


1) Register POS system – Represents overall ‗system‘, ‗root object‘
2) Process Sale handler – Represents receiver/handler of system events.

Department of IT, Sri Sai Ram Engineering College Page 11


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN
The choice of which is the most appropriate controller is influenced by other factors.

controller choices
The system operations are assigned to the controller classes like,

Allocation of system operations


A controller should assign other objects the work that needs to be done.
It coordinates or controls the activity. Same controller class can be used for all
system events to maintain information about the state of usecase.
A common defect in the design of controllers is it suffers from bad cohesion.
Controllers

The facade controller represents the overall system, device or a sub system.

Choose some class name that suggests a cover or faced over other layers of the application
that provides main service calls from UI layer down to the other layers.

Department of IT, Sri Sai Ram Engineering College Page 12


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Facade controllers are used


1) Where there are not ―too manyǁ system events
2) When the UI (User Interface) cannot redirect system event messages.

In used case controller there is a different controller for each use case. Facade
controllers lead to low cohesion or high coupling design.

So use case controllers are good when there are many system events across different
processes.
• Boundary objects
• Entity objects
• Control objects

Boundary : Abstractions of the interfaces


objects
Entity objects :
Application independent domain software
objects
Control objects : Use case handless
An important corollary of the controller pattern is UI objects.

System operations should be handled in application logic or domain layer of objects


rather than UI layer of a system.

Web UIs and saver side application of controller


An approach used is
ASP.NET and webforms:
• Developers insert application logic handling in the ―code behindǁ
file, mixing application logic into the UI layer.
• Server side web UI frameworks embody the concept of web MVC (Model –
view - controller) pattern.
• Choosing server technical frameworks strongly influence handling of
serverside system operation.
• To lower the coupling of UI, the clientside UI forwards the request to the local
client side controller.

Benefits

1) Increased potential for reuse and pluggable interfaces.


2) Opportunity to reason about the state of the use case.

Department of IT, Sri Sai Ram Engineering College Page 13


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN
Design Patterns
A design pattern is a general repeatable solution to a commonly occurring problem in
software design. A design pattern isn't a finished design that can be transformed directly into
code. It is a description or template for how to solve a problem that can be used in many
different situations.

Designing for Visibility

The ability of one object to have reference of another is called visibility.


Example:
The getProductDescription message sent from a Register to a product catalog means
that ProductCatalog instance is visible to register.

Visibility from register to Product catalog


Ways of visibility: from Object A to Object B

1) Attribute visibility – B is an attribute of A


2) Parameter visibility – B is a parameter of a method of A
3) Local visibility – B is a local object in a method of A
4) Global visibility – B is globally visible in some way

Department of IT, Sri Sai Ram Engineering College Page 14


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Motivation of visibility

For an object A to send a message to an object B, B must be visible to A.

Attribute visibility

• It is a permanent visibility.
• Attribute visibility from A to B exists if B is attribute of A.
• It persists as long as A and B exists
Example
Register has attribute visibility to ProductCatalog, because it is an attribute to Register.

Attribute visibility
Parameter visibility

Here B passes as parameter to A when parameter visibility


exists. It persists only within the scope of the method.
So it is relatively temporary visibility.

Example:
When makeLineItem is sent to a sale instance, a ProductDescription instance is
passed as a parameter.

Department of IT, Sri Sai Ram Engineering College Page 15


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Parameter visibility

Local visibility

It exists from A to B when B is declared as a local object within a method of A.


It persists only within the scope of the method. So it is relatively temporarily
visible. The local visibility is achieved by
• Creating a new local instance and assigning to a local variable
• Assign the returning object from a method invocation to a local variable.

Local visibility
Global visibility

Here global visibility is achieved from A to B if B is


global to A. It persists as long as A and B exist. So it is
permanent visibility. To achieve global visibility,
(i) Assign instance to global variable in languages like C++.
(ii) To use ‗Singleton‘ pattern.

Department of IT, Sri Sai Ram Engineering College Page 16


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

CREATIONAL DESIGN PATTERNS

Creational design patterns are design patterns that deal with object creation mechanisms,
trying to create objects in a manner suitable to the situation. The basic form of object creation
could result in design problems or in added complexity to the design. Creational design
patterns solve this problem by somehow controlling this object creation.
Creational design patterns are composed of two dominant ideas. One is encapsulating
knowledge about which concrete classes the system uses. Another is hiding how instances of
these concrete classes are created and combined.
Creational design patterns are further categorized into object-creational patterns and Class-
creational patterns, where Object-creational patterns deal with Object creation and Class-
creational patterns deal with Class-instantiation. In greater details, Object-creational patterns
defer part of its object creation to another object, while Class-creational patterns defer its
object creation to subclasses.
Five well-known design patterns that are parts of creational patterns are the

1. Abstract Factory: Creates an instance of several families of classes. Provide an


interface for creating families of related or dependent objects without specifying their
concrete classes.
2. Builder: Separates object construction from its representation. Separate the construction
of a complex object from its representation so that the same construction processes can
create different representations.
3. Factory Method: Creates an instance of several derived classes. Define an interface for
creating an object, but let subclasses decide which class to instantiate. Factory Method
lets a class defer instantiation to subclasses.
4. Prototype: A fully initialized instance to be copied or cloned. Specify the kinds of
objects to create using a prototypical instance, and create new objects by copying this
prototype.
5. Singleton: A class of which only a single instance can exist. Ensure a class only has one
instance, and provide a global point of access to it.

Factory Method
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.
 Defining a "virtual" constructor.
 The new operator considered harmful.

Department of IT, Sri Sai Ram Engineering College Page 17


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Problem : For complex creation logic, for better cohesion who is responsible for creating
objects.
Solution : A pure fabrication object called ‗factory‘ is created that handles creation.
In Service Factory‘, the logic to decide the class creation is resolved by reading
in the class name from external source.
Discussion:

 Factory Method is to creating objects as Template Method is to implementing an


algorithm. A superclass specifies all standard and generic behavior (using pure virtual
"placeholders" for creation steps), and then delegates the creation details to subclasses
that are supplied by the client.
 Factory Method makes a design more customizable and only a little more
complicated. Other design patterns require new classes, whereas Factory Method only
requires a new operation.
 People often use Factory Method as the standard way to create objects; but it isn't
necessary if: the class that's instantiated never changes, or instantiation takes place in
an operation that subclasses can easily override (such as an initialization operation).

 Factory Method is similar to Abstract Factory (Provide an interface for creating


families of related or dependent objects without specifying their concrete classes) but
without the emphasis on families.

 Factory Methods are routinely specified by an architectural framework, and then


implemented by the user of the framework.

Department of IT, Sri Sai Ram Engineering College Page 18


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Example:

The Factory Method defines an interface for creating objects, but lets subclasses decide
which classes to instantiate. Injection molding presses demonstrate this pattern.
Manufacturers of plastic toys process plastic molding powder, and inject the plastic into
molds of the desired shapes. The class of toy (car, action figure, etc.) is determined by the
mold.

Advantages :

(i) Separate the responsibility of complex creation into cohesive helper objects.
(ii) Potential complex creation is hidden.
(iii) Performance-enhancing memory management strategies such as object
catching or recycling are allowed.

STRUCTURAL DESIGN PATTERNS

Structural Design Patterns are Design Patterns that ease the design by identifying a simple
way to realize relationships between entities.

The well known design patterns that are parts of Structural patterns are the

1. Adapter: Match interfaces of different classes. Convert the interface of a class into
another interface clients expect. Adapter lets classes work together that couldn’t
otherwise because of incompatible interfaces.
2. Bridge: Separates an object’s interface from its implementation. Decouple an abstraction
from its implementation so that the two can vary independently.
3. Composite: A tree structure of simple and composite objects. Compose objects into tree
structures to represent part-whole hierarchies. Composite lets clients treat individual
objects and compositions of objects uniformly.

Department of IT, Sri Sai Ram Engineering College Page 19


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

4. Decorator: Add responsibilities to objects dynamically. Attach additional


responsibilities to an object dynamically. Decorators provide a flexible alternative to sub
classing for extending functionality.
5. Facade: A single class that represents an entire subsystem. Provide a unified interface to
a set of interfaces in a system. Facade defines a higher-level interface that makes the
subsystem easier to use.
6. Flyweight: A fine-grained instance used for efficient sharing. Use sharing to support
large numbers of fine-grained objects efficiently. A flyweight is a shared object that can
be used in multiple contexts simultaneously. The flyweight acts as an independent object
in each context — it’s indistinguishable from an instance of the object that’s not shared.
7. Proxy: An object representing another object. Provide a surrogate or placeholder for
another object to control access to it.

Adapter:
Intent
 Convert the interface of a class into another interface clients expect. Adapter lets
classes work together that couldn't otherwise because of incompatible interfaces.
 Wrap an existing class with a new interface.
 Impedance match an old component to a new system

Problem : If similar components have different interfaces then how to


resolve incompatible interfaces.
Solution : Using an intermediate adapter object, convert original interface
of a component to another interface.
Example:
The NextGen POS system supports many third party services like,
• Tax calculators
• Credit authorization services
• Inventory systems
• Accounting systems etc
Add a level of indirection with objects to adapt to the solution.

Department of IT, Sri Sai Ram Engineering College Page 20


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Adapter pattern
Here a particular adapter will be instantiated such as
• SAP for accounting
• SOAP XML interface for intranet web services.

Using an Adapter

Department of IT, Sri Sai Ram Engineering College Page 21


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Type names are given by pattern name, ―Adapter, to communicate the user of the design
pattern being used.

A resource adapter that hides external system is considered as façade object.

The motivation to call resource adapter exist when wrapping objects provide
adaptation.

Bridge: Intent
 Decouple an abstraction from its implementation so that the two can vary
independently.
 Publish interface in an inheritance hierarchy, and bury implementation in its own
inheritance hierarchy.
 Beyond encapsulation, to insulation

Problem
"Hardening of the software arteries" has occurred by using subclassing of an abstract base
class to provide alternative implementations. This locks in compile-time binding between
interface and implementation. The abstraction and implementation cannot be independently
extended or composed.

Motivation
Consider the domain of "thread scheduling".

There are two types of thread schedulers, and two types of operating systems or "platforms".
Given this approach to specialization, we have to define a class for each permutation of these
two dimensions. If we add a new platform (say ... Java's Virtual Machine), what would our
hierarchy look like?

Department of IT, Sri Sai Ram Engineering College Page 22


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

What if we had three kinds of thread schedulers, and four kinds of platforms? What if we had
five kinds of thread schedulers, and ten kinds of platforms? The number of classes we would
have to define is the product of the number of scheduling schemes and the number of
platforms.

The Bridge design pattern proposes refactoring this exponentially explosive inheritance
hierarchy into two orthogonal hierarchies – one for platform-independent abstractions, and
the other for platform-dependent implementations.

Discussion
Decompose the component's interface and implementation into orthogonal class hierarchies.
The interface class contains a pointer to the abstract implementation class. This pointer is
initialized with an instance of a concrete implementation class, but all subsequent interaction
from the interface class to the implementation class is limited to the abstraction maintained in
the implementation base class. The client interacts with the interface class, and it in turn
"delegates" all requests to the implementation class.

The interface object is the "handle" known and used by the client; while the implementation
object, or "body", is safely encapsulated to ensure that it may continue to evolve, or be
entirely replaced (or shared at run-time.

Use the Bridge pattern when:

 We want run-time binding of the implementation,


 We have a proliferation of classes resulting from a coupled interface and numerous
implementations,
 We want to share an implementation among multiple objects,
 We need to map orthogonal class hierarchies.

Consequences include:

 Decoupling the object's interface,


 Improved extensibility (you can extend (i.e. subclass) the abstraction and
implementation hierarchies independently),
 Hiding details from clients.

Bridge is a synonym for the "handle/body" idiom. This is a design mechanism that
Department of IT, Sri Sai Ram Engineering College Page 23
CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

encapsulates an implementation class inside of an interface class. The former is the body, and
the latter is the handle. The handle is viewed by the user as the actual class, but the work is
done in the body. "The handle/body class idiom may be used to decompose a complex
abstraction into smaller, more manageable classes. The idiom may reflect the sharing of a
single resource by multiple classes that control access to it (e.g. reference counting)."

Example
The Bridge pattern decouples an abstraction from its implementation, so that the two can vary
independently. A household switch controlling lights, ceiling fans, etc. is an example of the
Bridge. The purpose of the switch is to turn a device on or off. The actual switch can be
implemented as a pull chain, simple two position switch, or a variety of dimmer switches.

BEHAVIOURAL DESIGN PATTERNS


Behavioural 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.
The well known design patterns that are parts of behavioural patterns are the

1. Chain of Responsibility : A way of passing a request between a chain of objects.


Avoid coupling the sender of a request to its receiver by giving more than one object
a chance to handle the request. Chain the receiving objects and pass the request along
the chain until an object handles it.
2. Command: Encapsulate a command request as an object. Encapsulate a request as an
object, thereby letting you parameterize clients with different requests, queue or log
requests, and support undoable operations.
3. Interpreter: A way to include language elements in a program. Given a language,
define a representation for its grammar along with an interpreter that uses the
representation to interpret sentences in the language.
4. Iterator: Sequentially access the elements of a collection. Provide a way to access the
elements of an aggregate object sequentially without exposing its underlying
Department of IT, Sri Sai Ram Engineering College Page 24
CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

representation.
5. Mediator: Defines simplified communication between classes. Define an object that
encapsulates how a set of objects interact. Mediator promotes loose coupling by
keeping objects from referring to each other explicitly, and it lets you vary their
interaction independently.
6. Memento: Capture and restore an object's internal state. Without violating
encapsulation, capture and externalize an object’s internal state so that the object can
be restored to this state later.
7. Observer: A way of notifying change to a number of classes. Define a one-to-many
dependency between objects so that when one object changes state, all its dependents
are notified and updated automatically.
8. State: Alter an object's behavior when its state changes. Allow an object to alter its
behavior when its internal state changes. The object will appear to change its class.
9. Strategy: Encapsulates an algorithm inside a class. Define a family of algorithms,
encapsulate each one, and make them interchangeable. Strategy lets the
algorithm vary independently from clients that use it.
10. Template: Defer the exact steps of an algorithm to a subclass. Define the skeleton of
an algorithm in an operation, deferring some steps to subclasses. Template Method
lets subclasses redefine certain steps of an algorithm without changing the
algorithm’s structure.
11. Visitor: Defines a new operation to a class without change. Represent an operation
to be performed on the elements of an object structure. Visitor lets you define a new
operation without changing the classes of the elements on which it operates.

Strategy:

Intent

 Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from the clients that use it.
 Capture the abstraction in an interface, bury implementation details in derived classes.

Problem
One of the dominant strategies of object-oriented design is the "open-closed principle".

Figure demonstrates how this is routinely achieved - encapsulate interface details in a base
class, and bury implementation details in derived classes. Clients can then couple themselves
to an interface, and not have to experience the upheaval associated with change: no impact
when the number of derived classes changes, and no impact when the implementation of a
derived class changes.

Department of IT, Sri Sai Ram Engineering College Page 25


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

A generic value of the software community for years has been, "maximize cohesion and
minimize coupling". The object-oriented design approach shown in figure is all about
minimizing coupling. Since the client is coupled only to an abstraction (i.e. a useful fiction),
and not a particular realization of that abstraction, the client could be said to be practicing
"abstract coupling" . an object-oriented variant of the more generic exhortation "minimize
coupling".

A more popular characterization of this "abstract coupling" principle is "Program to an


interface, not an implementation".

Clients should prefer the "additional level of indirection" that an interface (or an abstract base
class) affords. The interface captures the abstraction (i.e. the "useful fiction") the client wants
to exercise, and the implementations of that interface are effectively hidden.

Example
A Strategy defines a set of algorithms that can be used interchangeably. Modes of
transportation to an airport is an example of a Strategy. Several options exist such as driving
one's own car, taking a taxi, an airport shuttle, a city bus, or a limousine service. For some
airports, subways and helicopters are also available as a mode of transportation to the airport.
Any of these modes of transportation will get a traveler to the airport, and they can be used
interchangeably. The traveler must chose the Strategy based on trade-offs between cost,
convenience, and time.

Department of IT, Sri Sai Ram Engineering College Page 26


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Observer: Intent
 Define a one-to-many dependency between objects so that when one object changes
state, all its dependents are notified and updated automatically.
 Encapsulate the core (or common or engine) components in a Subject abstraction, and
the variable (or optional or user interface) components in an Observer hierarchy.
 The "View" part of Model-View-Controller.

Problem: Subscriber objects are interested in state changes or events of a publisher object, want to
react in their own unique way when the publisher generates an event.
Solution: Subscriber - implements this interface. Publisher dynamically registers Subscribers
interest in an event and notifies them when event occurs.
Discussion
Define an object that is the "keeper" of the data model and/or business logic (the Subject).
Delegate all "view" functionality to decoupled and distinct Observer objects. Observers
register themselves with the Subject as they are created. Whenever the Subject changes, it
broadcasts to all registered Observers that it has changed, and each Observer queries the
Subject for that subset of the Subject's state that it is responsible for monitoring.

This allows the number and "type" of "view" objects to be configured dynamically, instead of
being statically specified at compile-time.

The protocol described above specifies a "pull" interaction model. Instead of the Subject
"pushing" what has changed to all Observers, each Observer is responsible for "pulling" its
particular "window of interest" from the Subject. The "push" model compromises reuse,
while the "pull" model is less efficient.

Issues that are discussed, but left to the discretion of the designer, include: implementing
event compression (only sending a single change broadcast after a series of consecutive
changes has occurred), having a single Observer monitoring multiple Subjects, and ensuring
that a Subject notify its Observers when it is about to go away.

The Observer pattern captures the lion's share of the Model-View-Controller architecture that
has been a part of the Smalltalk community for years.

Structure

Department of IT, Sri Sai Ram Engineering College Page 27


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Subject represents the core (or independent or common or engine) abstraction. Observer
represents the variable (or dependent or optional or user interface) abstraction. The Subject
prompts the Observer objects to do their thing. Each Observer can call back to the Subject as
needed.
Example
The Observer defines a one-to-many relationship so that when one object changes state, the
others are notified and updated automatically. Some auctions demonstrate this pattern. Each
bidder possesses a numbered paddle that is used to indicate a bid. The auctioneer starts the
bidding, and "observes" when a paddle is raised to accept the bid. The acceptance of the bid
changes the bid price which is broadcast to all of the bidders in the form of a new bid.

Applying GOF Design Patterns

Design patterns represent common software problems and the solutions to those problems in
a formal manner. They were inspired by a book written by architect Christopher Alexander.
Patterns were introduced in the software world by another book: "Design Patterns: Elements
of Reusable Object-Oriented Software", by Erich Gamma, Richard Helm, Ralph Johnson, and
John Vlissides. These people were nicknamed the "Gang of Four" for some mysterious
reason. The Gang of Four describes 23 design patterns. With patterns you don't have to
reinvent the wheel and get proven solutions for frequently encountered problems. Many
books and articles have been written on this subject. This means that design patterns are
becoming common knowledge, which leads to better communication. To summarize design
patterns save time, energy while making your life easier.

Singleton:
Motivation
Sometimes it's important to have only one instance for a class. For example, in a system there
should be only one window manager (or only a file system or only a print spooler). Usually
singletons are used for centralized management of internal or external resources and they
Department of IT, Sri Sai Ram Engineering College Page 28
CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

provide a global point of access to themselves.


The singleton pattern is one of the simplest design patterns: it involves only one class which
is responsible to instantiate itself, to make sure it creates not more than one instance; in the
same time it provides a global point of access to that instance. In this case the same instance
can be used from everywhere, being impossible to invoke directly the constructor each time.

Intent

 Ensure that only one instance of a class is created.


 Provide a global point of access to the object.

Implementation

The implementation involves a static member in the "Singleton" class, a private constructor
and a static public method that returns a reference to the static member.

The Singleton Pattern defines a getInstance operation which exposes the unique instance
which is accessed by the clients. getInstance() is is responsible for creating its class unique
instance in case it is not created yet and to return that instance.

Example
The Singleton pattern ensures that a class has only one instance and provides a global point of
access to that instance. It is named after the singleton set, which is defined to be a set
containing one element. 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.

Department of IT, Sri Sai Ram Engineering College Page 29


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Factory Method

The Factory Method pattern deals with situations where at runtime one of several
similar classes must be created. Visualize this as a factory that produces objects. In a toy
factory for instance we have the abstract concept of toy. Every time we get a request for a
new toy a decision must be made - what kind of a toy to manufacture. Similarly to the
Singleton pattern the Factory Method pattern utilises a public static accessor method. In our
example the abstract Toy factory class will have a getInstance() method, which is inherited
by its non abstract subclasses.

Adapter

Sometimes you will have two classes that can in principle work well together, but
they can't interface with each other for some reason. This kind of problem occurs when
travelling abroad and you carry an electric shaver with you. Although it will work perfectly
when you are at home. There can be problems in a foreign country, because of a different
standard voltage. The solution is to use an adapter. Let's turn our attention back to the
software domain. Here we will have an interface which defines new methods for example
getElectricity2. An adapter class will wrap around the Shaver class. The adapter class will
implement the interface with the new method.

Proxy

The Proxy pattern deals with situations where you have a complex object or it takes a
long time to create the object. The solution to this problem is to replace the complex object
with a simple 'stub' object that has the same interface. The stub acts as a body double. This is
the strategy used by the Java Remote Method Invocation API. The reason to use the proxy

Department of IT, Sri Sai Ram Engineering College Page 30


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

pattern in this case is that the object is on a remote server causing network overhead. Other
reasons to use the proxy can be restricted access (Java applets for example) or time
consuming calculations.

Decorator

The Decorator is usually a subclass, that is a body double for its superclass or another
class with identical interface. The goal of the Decorator pattern is to add or improve the
capabilities of the super class.

Composite

The composite is often encountered in GUI packages like for instance the Java
Abstract Windwing Toolkit (AWT) or Microsoft Foundation (MFC) classes. All objects in
this pattern have a common abstract superclass that descibes basic object conduct. The base
class in the MFC hierarchy is CObject. It provides functions for debugging and serialization.
All the MFC classes even the most basic ones inherit these facilities.

Observer and MVC

An application with Model - View - Controller setup usually uses the Observer
Pattern. In a Java webserver environment the model will be represented by Java classes
encompassing the business logic, the view is represented by Java Server Pages which display

Department of IT, Sri Sai Ram Engineering College Page 31


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

HTML in the client's browser and we will have a Servlets as Controllers. The observer
pattern strategy is to have view components take subscriptions for their model. This ensures
that they will get notified if the model changes.

Template

In the good old days before OOP writing functions was the recommended thing to do.
A sort algorithm would be implement by half dozen of functions, one sort function for
integers, one sort function for floating points, one sort function for doubles etc. These
functions are so similar that nobody in their right mind will type them letter by letter. Instead
a programmer will write a template and copy the template several times. After that it's just a
matter of writing down datatypes as appropriate. Thanks to OOP and the Template Design
Pattern less code is required for this task. First we need to define an abstract Template class
let's call it SortTemplate and it will have methods sort, compare and process (performs one
cycle of the algorithm). Then we define concrete classes for each datatype. These classes are
subclasses of SortTemplate and implement the compare and process methods.

Strategy

The Strategy Design Pattern makes it possible choose an implementation of an


algorithm at run time. The implementation classes implement the same interface. In the case
of the Java AWT Layout classes, the common interface is LayoutManager.

Department of IT, Sri Sai Ram Engineering College Page 32


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Mapping Design to Code:

Implementation in an object-oriented language requires writing source code for:

 class and interface definitions


 method definitions

The following sections discuss their generation in Java (as a typical case). The discussion is
more-or-less independent of using a UML tool for code generation or working from some
wall sketches.
Creating Class Definitions from DCDs (Define Class Diagrams)
At the very least, DCDs depict the class or interface name, superclasses, operation signatures,
and attributes of a class. This is sufficient to create a basic class definition in an OO
language. If the DCD was drawn in a UML tool, it can generate the basic class definition
from the diagrams.

Defining a Class with Method Signatures and Attributes


From the DCD, a mapping to the attribute definitions (Java fields) and method signatures for
the Java definition of SalesLineItem is straightforward, as shown in fig:

public class SalesLineItem


{
private int quantity;

private ProductDescription description;

public SalesLineItem(ProductDescription desc, int qty)

{ ... } public Money getSubtotal() { ... }

SalesLine
m description description :
Text

Note the addition in the source code of the Java constructor SalesLineItem(ノ). It is derived
from the create(desc, qty) message sent to a SalesLineItem in the enterItem interaction
diagram. This indicates, in Java, that a constructor supporting these parameters is required.
The create method is often excluded from the class diagram because of its commonality and
multiple interpretations, depending on the target language.
Creating Methods from Interaction Diagrams
The sequence of the messages in an interaction diagram translates to a series of statements in
the method definitions. The enterItem interaction diagram in Figure illustrates the Java
definition of the enterItem method. For this example, we will explore the implementation of
the Register and its enterItemmethod. A Java definition of the Register class is shown in Fig:

Department of IT, Sri Sai Ram Engineering College Page 33


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

The enterItem message is sent to a Register instance; therefore, the enterItem method is
defined in class Register.

public void enterItem(ItemID itemID, int qty)

Message 1: A getProductDescription message is sent to the ProductCatalog to retrieve


a ProductDescription.

ProductDescription desc = catalog.getProductDescription(itemID);

Message 2: The makeLineItem message is sent to the Sale.

currentSale.makeLineItem(desc, qty);

In summary, each sequenced message within a method, as shown on the interaction diagram,
is mapped to a statement in the Java method.

The complete enterItem method and its relationship to the interaction diagram is shown
in Fig:

Department of IT, Sri Sai Ram Engineering College Page 34


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

The Register.enterItem Method

Collection Classes in Code


One-to-many relationships are common. For example, a Sale must maintain visibility to a
group of many SalesLineItem instances, as shown in Figure . In OO programming languages,
these relationships are usually implemented with the introduction of a collection object, such
as a List or Map, or even a simple array.

Department of IT, Sri Sai Ram Engineering College Page 35


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

For example, the Java libraries contain collection classes such as ArrayList and HashMap,
which implement the List and Map interfaces, respectively. Using ArrayList, the Sale class
can define an attribute that maintains an ordered list of SalesLineItem instances.

The choice of collection class is of course influenced by the requirements; key-based lookup
requires the use of a Map, a growing ordered list requires a List, and so on.

As a small point, note that the lineItems attribute is declared in terms of its interface.

Guideline: If an object implements an interface, declare the variable in terms of the interface,
not the concrete class.

For example, in Figure the definition for the lineItems attribute demonstrates this guideline:

private List lineItems = new ArrayList();

Exceptions and Error Handling


Exception handling has been ignored so far in the development of a solution. This was
intentional to focus on the basic questions of responsibility assignment and object design.
However, in application development, it's wise to consider the large-scale exception handling
strategies during design modeling (as they have a large-scale architectural impact), and
certainly during implementation. Briefly, in terms of the UML, exceptions can be indicated in
the property strings of messages and operation declarations.
Defining the Sale.makeLineItem Method
As a final example, the makeLineItem method of class Sale can also be written by inspecting
the enterItem collaboration diagram. An abridged version of the interaction diagram, with the
accompanying Java method, is shown in Figure

Department of IT, Sri Sai Ram Engineering College Page 36


CS8592 – OBJECT ORIENTED ANALYSIS AND DESIGN

Order of Implementation
Classes need to be implemented (and ideally, fully unit tested) from least-coupled to most
coupled. For example, possible first classes to implement are
either Payment or ProductDescription; next are classes only dependent on the prior
implementations—ProductCatalog or SalesLineItem.

Department of IT, Sri Sai Ram Engineering College Page 37

You might also like