OOAD - Unit 4
OOAD - Unit 4
GRASP
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.
1. Knowing
2. Doing
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?
Example:
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
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.
Problem statement: Who's responsible for knowing the grand total of a Sale?
After knowing and answering subtotal, a SalesLineItem has to know product price.
ProductDescription is an information expert for answering price.
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
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:
Types of Coupling:
Example
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.
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.
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
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ǁ.
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:
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
controller choices
The system operations are assigned to the controller classes like,
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.
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
Benefits
Motivation of visibility
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
Example:
When makeLineItem is sent to a sale instance, a ProductDescription instance is
passed as a parameter.
Parameter visibility
Local visibility
Local visibility
Global visibility
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
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.
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:
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 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.
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
Adapter pattern
Here a particular adapter will be instantiated such as
• SAP for accounting
• SOAP XML interface for intranet web services.
Using an Adapter
Type names are given by pattern name, ―Adapter, to communicate the user of the design
pattern being used.
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?
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.
Consequences include:
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.
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.
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".
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.
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
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.
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
Intent
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.
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
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.
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
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 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.
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:
The enterItem message is sent to a Register instance; therefore, the enterItem method is
defined in class Register.
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:
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:
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.