Download as pdf or txt
Download as pdf or txt
You are on page 1of 29

UNIT IV DESIGN PATTERNS

GRASP: Designing objects with responsibilities – Creator – Information expert – Low Coupling
– High Cohesion – Controller
Design Patterns – creational – factory method – structural – Bridge – Adapter – behavioural
– Strategy – observer –Applying GoF design patterns – Mapping design to code

Pattern
A pattern is a named description of a problem and solution that can be applied to new
contexts; ideally, a pattern advice on how to apply its solution in varying circumstances and
considers the forces and trade-offs. It is a three-part rule, which expresses a relation between a
certain context, a problem, and a solution.
Example:
• Pattern Name: Information Expert
• Problem: What is a basic principle by which to assign responsibilities to objects?
• Solution: Assign a responsibility to the class that has the information needed to fulfill it.
Advantages
• Design patterns enable large scale reuse of software architectures and also help document
systems
• Patterns help improve developer communication
• Pattern names form a common vocabulary
• Patterns help ease the transition to object oriented technology
Drawbacks
• Patterns do not lead to direct code reuse
• Patterns are deceptively simple
• Teams may suffer from pattern download
• Patterns are validated by experience and discussion rather than by automated testing
• Integrating patterns is a human intensive activity

General Responsibility Assignment Software Patterns (GRASP)


The GRASP patterns are a learning aid to help one understand essential object design,
and apply design reasoning in a methodical, rational, explainable way. This approach to
understanding and using design principles is based on patterns of assigning responsibilities.

Designing objects with Responsibilities


The UML defines a responsibility as “a contract or obligation of a classifier”.
Responsibilities are related to the obligations of an object in terms of its behavior. Basically,
these responsibilities are of the following two types:
• knowing
• doing
Doing responsibilities of an object include:
• doing something itself, such as creating an object or doing a calculation
• initiating action in other objects
• controlling and coordinating activities in other objects
Knowing responsibilities of an object include:
• knowing about private encapsulated data
Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 1
• knowing about related objects
• knowing about things it can derive or calculate

Responsibilities are assigned to classes of objects while coding or while modeling.


Example:
o “a Sale is responsible for creating SalesLineltems” (a doing)
o “a Sale is responsible for knowing its total” (a knowing)
• Determining the assignment of responsibilities often occurs during the creation of
interaction diagrams, and certainly during programming.

Responsibilities and Interaction Diagrams


Within the UML artifacts, a common context where these responsibilities (implemented
as methods) are considered is during the creation of interaction diagrams.

Figure 16.1 indicates that Sale objects have been given a responsibility to create Payments,
which is invoked with a makePayment message and handled with a corresponding makePayment
method. Furthermore, the fulfillment of this responsibility requires collaboration to create the
SalesLineltem object and invoke its constructor.

Object Design with GRASP: Nine GRASP patterns/principles

Pattern Description/Role
Information A general principle of object design and responsibility assignment?
Expert Assign a responsibility to the information expert — the class that has the
information necessary to fulfill the responsibility.
Creator Who creates? (Note that Factory is a common alternate solution.)
Assign class B the responsibility to create an instance of class A if one of these
is true:
1. B contains A 4. B records A
2. B aggregates A 5. B closely uses A
3. B has the initializing data for A
Controller Who handles a system event?
Assign the responsibility for handling a system event message to a class

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 2
representing one of these choices:
1. Represents the overall system, device, or a subsystem (facade controller).
2. Represents a use case scenario within which the system event occurs (use-
case or session controller)
Low Coupling How to support low dependency and increased reuse?
(evaluative) Assign responsibilities so that (unnecessary) coupling remains low.
High Cohesion How to keep complexity manageable?
(evaluative) Assign responsibilities so that cohesion remains high.
Polymorphism Who is responsible when behavior varies by type?
When related alternatives or behaviors vary by type (class), assign
responsibility for the behavior — using polymorphic operations — to the types
for which the behavior varies.
Pure Who is responsible when you are desperate, and do not want to violate high
Fabrication cohesion and low coupling?
Assign a highly cohesive set of responsibilities to an artificial or convenience
"behavior" class that does not represent a problem domain concept —
something made up, in order to support high cohesion, low coupling, and reuse.
Indirection How to assign responsibilities to avoid direct coupling?
Assign the responsibility to an intermediate object to mediate between other
components or services, so that they are not directly coupled.
Protected How to assign responsibilities to objects, subsystems, and systems so that the
Variations variations or instability in these elements do not have an undesirable impact on
other elements?
Identify points of predicted variation or instability; assign responsibilities to
create a stable "interface" around them.

CASE STUDY: The NextGen POS (Point of Sale) System


A POS system is a computerized application used to record sales and handle payments; it
is typically used in a retail store. It includes hardware components such as a computer and bar
code scanner, and software to run the system. It interfaces to various service applications, such as
a third-party tax calculator and inventory control. These systems must be relatively fault-tolerant;
that is, even if remote services are temporarily unavailable (such as the inventory system), they
must still be capable of capturing sales and handling at least cash payments.
A POS system increasingly must support multiple and varied client-side terminals and
interfaces. These include a thin-client Web browser terminal, a regular personal computer with
something like a Java Swing graphical user interface, touch screen input, wireless PDAs, and so
forth.
Furthermore, we are creating a commercial POS system that we will sell to different
clients with disparate needs in terms of business rule processing. Each client will desire a unique
set of logic to execute at certain predictable points in scenarios of using the system, such as when
a new sale is initiated or when a new line item is added.
Using an iterative development strategy, we are going to proceed through requirements,
object-oriented analysis, design, and implementation.

CASE STUDY: Monopoly Game


Monopoly is a board game where players roll two six-sided dice to move around the
game board, buying and trading properties, and develop them with houses and hotels. Players

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 3
collect rent from their opponents, with the goal being to drive them into bankruptcy (Legal status
of a person cannot repay debts to creditors).
Preparation
To begin, place the game board on the table. Each player selects a token. Then they place
their token on the table near the space labeled Go, placing it on Go only when his/her first turn to
move arrives. One player becomes the Banker, who distributes assets from the Bank to the
players. Only the player in question can use their money, money can only be lent via the Banker
or by the player mortgaging an asset, money cannot be lent by another player. Each player is
given 1500 divided as follows: 2 each of 500’s, 100’s and 50’s; 6 20’s; 5 each of 10’s, 5’s and
1’s. The Bank never runs out of money; if it runs out of bills, players can use any convenient
items as substitutes until the Bank gets enough money. He/she also needs to make sure that they
collect $200 when they pass GO.
General Rules
• On a player's turn, the player must roll the dice and move his/her token forward the number
of spaces as rolled on the dice.
• If the player lands on an unowned property, the player may buy it for the price listed on that
property's space. If he or she agrees to buy it, he or she pays the Bank the amount shown on
the property space and receives the deed for that property. If he or she refuses to buy the
property for the amount stated on the deed, the property is auctioned. Bidding may start at
any price, and all players may bid. The highest bidder wins the property and pays the Bank
the amount bid and receives the property's title deed.
• If the player lands on an unmortgaged property owned by another player, he or she pays rent
to that person, as specified on the property's deed. It is the property owner's responsibility to
demand rent, and he or she has until the beginning of the second following player's turn to do
so.
• If the player lands on his or her own property, or on property which is owned by another
player but currently mortgaged, nothing happens.
• If the player lands on Luxury Tax/Super Tax, he or she must pay the Bank $100 (in some
editions of the game, only $75).
• If the player lands on Income Tax he or she must pay the Bank either $200 or 10% of his or
her total assets (cash on hand, property, houses and hotels). In some editions of the game, this
is a flat rate of $200.
• If the player lands on the Go to Jail square, he or she must move his token directly to Jail.
• If the player lands on or passes Go in the course of his or her turn, he or she receives $200
from the Bank.
• You may sell houses back to the Bank for half the purchase price or sell property deeds to
other players in the game.
• Players may not loan money to other players. Only the Bank can loan money, and then only
by mortgaging properties.

CREATOR
Problem
Who should be responsible for creating a new instance of some class?
Solution
Assign class B the responsibility to create an instance of class A if one or more of the
following is true:
• B aggregates A objects.
• B contains A objects.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 4
• B records instances of A objects.
• B closely uses A objects.
• B has the initializing data that will be passed to A when it is created (thus B is an Expert
with respect to creating A).
B is a creator of A objects.
If more than one option applies, prefer a class B which aggregates or contains class A.

Example 1: NextGen POS


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. Consider the partial domain model in Figure 16.7.

Since a Sale contains (in fact, aggregates) many SalesLineltem objects, the Creator
pattern suggests that Sale is a good candidate to have the responsibility of creating SalesLineltem
instances.
Partial Sequence diagram

This assignment of responsibilities requires that a makeLineltem method be defined in


Sale. The context in which these responsibilities were considered and decided upon was while
drawing an interaction diagram. The method section of a class diagram can then summarize the
responsibility assignment results, concretely realized as methods.

Example 2: Monopoly Game


Problem: Who creates the Square object?
Solution: Since no software classes are yet defined, look at the domain model in Figure 17.3.
Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 5
A software Board object contains software Square objects where activities take place.
Squares will always be a part of one Board, and Board manages their creation and destruction;
thus they are in a composite aggregation association with the Board. Hence software Board
object is a logical place to create Square software objects.
Partial Sequence diagram

Partial Class diagram

Contraindications
Often, creation requires significant complexity, such as using recycled instances for
performance reasons, conditionally creating an instance from one of a family of similar classes
based upon some external property value, and so forth. In these cases, it is advisable to delegate
creation to a helper class called a Factory rather than use the class suggested by Creator.
Benefits
Low coupling is supported, which implies lower maintenance dependencies and higher
opportunities for reuse. Coupling is probably not increased because the created class is likely
already visible to the creator class, due to the existing associations.
Related Patterns or Principles
• Low Coupling
• Factory
• Whole-Part describes a pattern to define aggregate objects that support encapsulation of
components.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 6
INFORMATION EXPERT (OR EXPERT)
Problem
What is a general principle of assigning responsibilities to objects?
Solution
Assign a responsibility to the information expert - the class that has the information
necessary to fulfill the responsibility.

Example 1: NextGen POS


Problem: Who should be responsible for knowing the grand total of a sale"?
Solution: By Information Expert, we should look for that class of objects that has the
information needed to determine the total.
a)What information is needed to determine the grand total?
A Sale instance contains these; therefore, by the guideline of Information Expert, Sale is
a suitable class of object for this responsibility; it is an information expert for the work.
b)What information is needed to determine the line item subtotal?
The SalesLineItem knows its quantity and its associated ProductSpecification.price;
therefore, by Expert, SalesLineItem should determine the subtotal; it is the information expert.
c)To fulfill the responsibility of knowing and answering its subtotal, a Sales-LineItem needs to
know the product price. The ProductSpecification is an information expert on answering its
price; therefore, a message must be sent to it asking for its price.
To fulfill the responsibility of knowing and answering the sale’s total, three
responsibilities were assigned to three design classes of objects as follows.
Design Class Responsibility
Sale knows sale total
SalesLineltem knows line item subtotal
ProductSpecification knows product price

Partial Collaboration and Class diagram

Example 2: Monopoly Game


Problem: Who knows about a Square object, given a key?

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 7
Solution: To be able to retrieve and present any one Square-given its name-a software Board
must know (have the information) about all the Squares. Therefore Board has the information
necessary to fulfill this responsibility.
Partial Sequence and Class diagram

Contraindications
There are situations where a solution suggested by Expert is undesirable, usually because
of problems in coupling and cohesion. Supporting a separation of major concerns improves
coupling and cohesion in a design.
Benefits
• Information encapsulation is maintained, since objects use their own information to fulfill
tasks.
• It supports low coupling, which leads to more robust and maintainable systems.
• Behavior is distributed across the classes that have the required information, thus
encouraging more cohesive "lightweight" class definitions that are easier to understand
and maintain.
• High cohesion is usually supported.
Related Patterns or Principles
• Low Coupling
• High Cohesion

LOW COUPLING

Coupling is a measure of how strongly one element is connected to, has knowledge of, or
relies on other elements. An element with low (or weak) coupling is not dependent on too many
other elements.
Example:
• classes, subsystems, systems, and so on.
Problem
How to support low dependency, low change impact, and increased reuse?
Solution
Assign a responsibility so that coupling remains low. We use low coupling to evaluate
existing designs or to evaluate the choice between new alternatives to choose a design whose
coupling is low.

Example 1: NextGen POS


Consider the following partial class diagram from a NextGen case study:

Problem: Assume we have a need to create a Payment instance and associate it with the Sale.
What class should be responsible for this?

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 8
Design 1: Register records a Payment, Register instance could then send an addPayment
message to the Sale, passing along the new Payment as a parameter. Creator pattern prefers this.

Design 2: Sale does the creation of a Payment, does not increase the coupling. Low coupling
pattern prefers this because it maintains overall lower coupling.

Example 2: Monopoly Game


Problem: Why Board over Dog?
Solution:
Design 1: In the Dog case, the Dog and the Board must both know about Square objects (Two
objects have coupling to Square).

Design 2: In the Board case, only Board must know about Square objects (One object has
coupling to Square). Hence Board design is better than the Dog design, in terms of supporting
the goal of low coupling.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 9
Problems for a class with high (or strong) coupling
• Changes in related classes force local changes.
• Harder to understand in isolation.
• Harder to reuse because its use requires the additional presence of the classes on which it
is dependent.
Contraindications
High coupling to stable elements and to pervasive elements is seldom a problem. For
example, a Java J2EE application can safely couple itself to the Java libraries (java.util, and so
on), because they are stable and widespread.
Benefits
• not affected by changes in other components
• simple to understand in isolation
• convenient to reuse
• tends to reduce the time, effort, and defects in modifying software
Related Patterns
• Protected Variation

CONTROLLER

A Controller is a non-user interface object responsible for receiving or handling a system


event. It is a kind of "facade" onto the domain layer from the interface layer. It defines the
method for the system operation. It is sometimes called the coordinator. It does not normally do
the work, but delegates it to other objects.

Problem
What first object beyond the UI layer receives and coordinates a system operation?
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”, a “root object”, a device that the software is running
within, or a major subsystem (facade controller).
• Represents a use case scenario within which the system event occurs, often named
<UseCaseName>Handler, <UseCaseName>Coordinator, or <Use-CaseName>Session
(use-case or session controller).
o Use the same controller class for all system events in the same use case scenario.
o Informally, a session is an instance of a conversation with an actor. Sessions can
be of any length, but are often organized in terms of use cases (use case sessions).
Example 1: NextGen POS
During analysis, system operations may be assigned to the class System. This does not
mean that a software class named System fulfills them during design. Rather, a controller class is
assigned the responsibility for system operations.
Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 10
Problem: Who should be the controller for system events such as enterltem and endSale?

Solution: By the Controller pattern, here are some choices:


• Represents the overall "system," “root object”, device, or subsystem - Register,
POSSystem
• Represents a receiver or handler of all system events of a use case scenario -
ProcessSaleHandler, ProcessSaleSession

Example 2: Monopoly Game


Problem: Who is the Controller for the playGame system operation?

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 11
Solution: By the Controller pattern, here are some choices:
• Represents the overall "system," or a “root object” - MonopolyGame
• Represents the use case or session – Play Monopoly Game

Types of controller
a)Facade controller
It represents the overall system, device, or a subsystem. The idea is to choose some class
name that suggests a cover, or facade, over the other layers of the application, and that provides
the main point of service calls from the UI layer down to other layers.
It could be
▪ An abstraction of the overall physical unit Eg. Register, TelecommSwitch,
Phone, or Robot;
▪ A class representing the entire software system Eg. POSSystem
▪ Any other concept which the designer chooses to represent the overall system
or a subsystem Eg. ChessGame if it was game software.
Facade controllers are suitable when there are not "too many" system events, or it is not
possible for the user interface (UI) to redirect system event messages to alternating controllers,
such as in a message processing system.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 12
b)Use-case controller
If a use-case controller is chosen, then there is a different controller for each use case. A
use-case controller is a good choice when there are many system events across different
processes; it factors their handling into manageable separate classes, and also provides a basis for
knowing and reasoning about the state of the current scenario in progress.
c)Bloated Controllers
Poorly designed, a controller class will have low cohesion – unfocused and handling too
many areas of responsibility; this is called a bloated controller. Signs of bloating include:
• There is only a single controller class receiving all system events in the system, and there
are many of them.
• The controller itself performs many of the tasks necessary to fulfill the system event,
without delegating the work.
• A controller has many attributes, and maintains significant information about the system
or domain, which should have been distributed to other objects, or duplicates information
found elsewhere.

Benefits
• Increased potential for reuse, and pluggable interfaces
• It is a reasonable choice for system operations occurring in specific sequence
Related Patterns
• Command
• Façade
• Layers
• Pure Fabrication

HIGH COHESION

In terms of object design, cohesion (or more specifically, functional cohesion) is a


measure of how strongly related and focused the responsibilities of an element are. An element
with highly related responsibilities, and which does not do a tremendous amount of work, has
high cohesion.
Example:
• classes, subsystems, and so on.

Problem
How to keep objects focused, understandable, and manageable, and as a side effect,
support Low Coupling?
Solution
Assign a responsibility so that cohesion remains high.

Example 1: NextGen POS


Problem: Assume we have a need to create a Payment instance and associate it with the Sale.
What class should be responsible for this?
Solution:
Design 1: Register records a Payment, Register instance could then send an addPayment
message to the Sale, passing along the new Payment as a parameter. Creator pattern prefers this.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 13
In this isolated example, this is acceptable; Imagine that there were fifty system
operations, all received by Register. If it did the work related to each, it would become a
"bloated" incohesive object. The point is not that this single Payment creation task in itself
makes the Register incohesive, but as part of a larger picture of overall responsibility assignment,
it may suggest a trend toward low cohesion.
Design 2: Delegates the payment creation responsibility to the Sale, supports higher cohesion in
the Register. High cohesion and Low coupling patterns prefer this.

Example 2: Monopoly Game


Problem: What Next?
Solution:
Design 1: The left-hand version is making the MonopolyGame object itself do all the work.
Design 2: The right-hand version is delegating and distributing work among objects. It better
supports High Cohesion than the left-hand version.

Varying degrees of functional cohesion


1. Very low cohesion - A class is solely responsible for many things in very different functional
areas.
2. Low cohesion - A class has sole responsibility for a complex task in one functional area. A
class with low cohesion suffer from the following problems:

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 14
• hard to comprehend
• hard to reuse
• hard to maintain
• delicate; constantly effected by change
3. High cohesion - A class has moderate responsibilities in one functional area and collaborates
with other classes to fulfill tasks.
4. Moderate cohesion - A class has lightweight and sole responsibilities in a few different areas
that are logically related to the class concept, but not to each other.

Contraindications
There are a few cases in which accepting lower cohesion is justified.
• One case is the grouping of responsibilities or code into one class or component to
simplify maintenance by one person - although be warned that such grouping may also
make maintenance worse.
• Because of overhead and performance implications associated with remote objects and
remote communication, it is sometimes desirable to create fewer and larger, less cohesive
server objects that provide an interface for many operations.
Benefits
• Clarity and ease of comprehension of the design is increased.
• Maintenance and enhancements are simplified.
• Low coupling is often supported.
• The fine grain of highly related functionality supports increased reuse because a cohesive
class can be used for a very specific purpose.
Related Pattern
• Modular design - Modularity is the property of a system that has been decomposed into
a set of cohesive and loosely coupled modules.

Difference between Coupling and Cohesion (AU Dec 2015 Marks 8)


Cohesion Coupling
Cohesion is the indication of the relationship Coupling is the indication of the
within module. relationships between modules.
Cohesion shows the module’s Coupling shows the
relative functional strength. relative independence among the modules.
Cohesion is a degree (quality) to which a Coupling is a degree to which a component /
component / module focuses on the single thing. module is connected to the other modules.
While designing you should strive for high While designing you should strive for low
cohesion i.e. a module focus on a single task coupling i.e. dependency between modules
(i.e., single-mindedness) with little interaction should be less.
with other modules of the system.
Cohesion is the kind of natural extension of data Making private fields, private methods and
hiding for example, class having all members non public classes provides loose coupling.
visible with a package having default visibility.
Cohesion is Intra – Module Concept. Coupling is Inter -Module Concept.
Various types-coincidental, logical, temporal, Various types-Data, control, common,
procedural, communication content

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 15
APPLYING Gang-of-Four (GoF) Design Patterns
The Gang of Four are the authors of the book, "Design Patterns: Elements of Reusable
Object-Oriented Software". This important book describes various development techniques and
pitfalls in addition to providing twenty-three object-oriented programming design patterns. The
four authors were Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides. Since the
book was written by four authors, these patterns have become known as the "Gang-of-Four"—or
"GoF"—patterns.

Three Types of GoF Patterns


1. Creational patterns
• Deal with initializing and configuring objects
Types
o Singleton: Guarantee access to a singular (sole) instance
o Simple Factory: Create specialized, complex objects
o Abstract Factory: Create a family of specialized factories
o Factory Method: Define an interface for creating an object, but let subclasses
decide which class to instantiate
o Builder: Construct a complex object step by step
o Prototype: Clone new instances from a prototype
o Lazy initialization: Delay costly creation until it is needed
2. Structural patterns:
• Composition of classes or objects
• Decouple interface and implementation of classes
Types
o Adapter: Converts interface of a class into one that clients expect
o Bridge: Links abstraction with many possible implementations
o Composite: Represents part-whole hierarchies as tree structures
o Decorator: Attach additional responsibilities to object dynamically
o Facade: Simplifies the interface for a subsystem
o Flyweight: Shares many fine-grained objects efficiently
o Proxy: Provides a surrogate or placeholder for another obj. to control access to it
3. Behavioral patterns
• Deal with dynamic interactions among societies of objects
• How they distribute responsibility
Types
o Chain of Responsibility: Request delegated to the responsible service provider
o Command: Request or Action is first-class object, hence storable
o Iterator: Aggregate and access elements sequentially
o Interpreter: Language interpreter for a small grammar
o Mediator: Coordinates interactions between its associates
o Memento: Snapshot captures and restores object states privately
o Observer: Observers update automatically when observed object changes
o State: Object whose behavior depends on its state
o Strategy: Abstraction for selecting one of many algorithms
o Template Method: Algorithm with some steps supplied by derived class
o Visitor: Operations applied to elements of a heterogeneous object structure

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 16
ADAPTER (GoF) – Structural Design Pattern

Adapter pattern works as a bridge between two incompatible interfaces. A real life
example could be a case of card reader which acts as an adapter between memory card and a
laptop. You plug-in the memory card into card reader and card reader into the laptop so that
memory card can be read via laptop.
Problem
How to resolve incompatible interfaces, or provide a stable interface to similar
components with different interfaces?
Solution
Convert the original interface of a component into another interface, through an
intermediate adapter object.

Example: NextGen POS


Problem: The NextGen POS system needs to support several kinds of external third-party
services, including tax calculators, credit authorization services, inventory systems, and
accounting systems, among others. Each has a different API, which can't be changed.
Solution: There are multiple external third-party tax calculators that must be supported (such as
Tax-Master and Good-As-Gold Tax-Pro). Each tax calculator has a different interface, and so
there is similar but varying behavior to adapt to each of these external fixed interfaces or APIs.
TaxCalculatorAdapter objects act as intermediaries to the external tax calculators. Via
polymorphism, they provide a consistent interface to the inner objects and hide the variations in
the external APIs.

Benefits
• Reduces coupling to implementation specific details
• Polymorphism and Indirection reveals essential behavior provided.
• Including name of design pattern in new class (e.g., TaxMaster) in class diagrams and
code communicates to other developers in terms of known design patterns
Demerits
• It makes the code complex and difficult to debug.
Related Pattern
• A resource adapter that hides an external system (another GoF pattern)
Note:
Protected Variations (GRASP Design Pattern)
By adding a level of indirection, an interface, and using polymorphism with various
ITaxCalculatorAdapter implementations, protection within the system from variations in external
APIs is achieved.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 17
Indirection and Polymorphism (GRASP Design Patterns)
TaxCalculatorAdapter objects act as intermediaries to the external tax calculators. Via
polymorphism, they provide a consistent interface to the inner objects and hide the variations in
the external APIs. By adding a level of indirection and adding polymorphism, the adapter objects
protect the inner design against variations in the external interfaces.
Pure fabrication ((GRASP Design Pattern)
A pure fabrication is a class that does not represent a concept in the problem domain,
specially made up to achieve low coupling, high cohesion, and the reuse potential thereof
derived. This kind of class is called a "service" in domain-driven design. All GoF design patterns
such as Adapter, Command, Strategy, and so on, are Pure Fabrications.

FACTORY (GoF) – Creational Design Pattern

The Factory pattern makes use of Factory methods to deal with the problem of creating
objects without exposing the creation logic to the client and refer to newly created object using a
common interface. Other design patterns require new classes whereas the factory method only
requires new operation.
Problem
Who should be responsible for creating objects when there are special considerations,
such as complex creation logic, a desire to separate the creation responsibilities for better
cohesion, and so forth?
Solution
Create a Pure Fabrication object called a Factory that handles the creation.

Example: NextGen POS


Problem: Who creates the adapters?
Solution: Apply the Factory pattern, in which a Pure Fabrication “factory” object is defined to
create objects.
Note that in the ServicesFactory, the logic to decide which class to create is resolved by
reading in the class name from an external source (for example, via a system property if Java is
used) and then dynamically loading the class. This is an example of a partial data-driven
design. Without changing the source code in this factory class, we can create instances of new
adapter classes by changing the property value and ensuring the new class is visible in the Java
class path for loading.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 18
Advantages
• Due to Factory method, the code becomes flexible and loosely coupled. The process of
object creation can be moved from client code to Factory class or its child classes.
• It brings the consistency in the code as the object creation is only by the Factory method.
• Separate the responsibility of complex creation into cohesive helper objects.
• Hide potentially complex creation logic.
• Allow introduction of performance-enhancing memory management strategies, such as
object caching or recycling.
Demerits
• While using the factory method design pattern, the class has to be re-factored.
• The subclass needs to provide its re-implementation for all the factory methods.
• The code becomes complex.
Related Pattern
Factories are often accessed with the Singleton pattern.

SINGLETON (GoF) - Creational Design Pattern

This pattern involves a single class which is responsible to create an object while making
sure that only single object gets created. This class provides a way to access its only object which
can be accessed directly without need to instantiate the object of the class.
Problem
Exactly one instance of a class is allowed—it is a "singleton". Objects need a global and
single point of access.
Solution
Define a static method of the class that returns the singleton.

Example: NextGen POS


Problem: The ServicesFactory raises another new problem in the design: Who creates the
factory itself, and how is it accessed?
Solution: Observe that only one instance of the factory is needed within the process. The
solution is the Singleton pattern.

Related Patterns The Singleton pattern is often used for Factory objects and Facade objects

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 19
STRATEGY (GoF) – Behavioral Design Pattern

There are common situations when classes differ only in their behaviour. For this case, it
is a good idea to isolate the algorithms in separate classes in order to have the ability to select
different algorithms at runtime.
Problem
How to design for varying, but related, algorithms or policies? How to design for the
ability to change these algorithms or policies?
Solution
Define each algorithm/policy/strategy in a separate class, with a common interface.
Example
Problem: The pricing strategy (which may also be called a rule, policy, or algorithm) for a sale
can vary. During one period it may be 10% off all sales, later it may be $10 off if the sale total is
greater than $200, and myriad other variations. How do we design for these varying pricing
algorithms?
Solution: Since the behavior of pricing varies by the strategy (or algorithm), we create multiple
SalePricingStrategy classes, each with a polymorphic getTotal method (see Figure 23.8). Each
getTotal method takes the Sale object as a parameter, so that the pricing strategy object can find
the pre-discount price from the Sale, and then apply the discounting rule.

Merits
• If one needs to have several different behaviors that the object to perform, it is much
simpler to keep track of them if each behavior is a separate class. One can add, remove,
or change any of the behaviors very easily.
• This strategy brings the flexibility in the code.
• When you have several objects that are basically the same, and differ only in their
behavior, it is a good idea to make use of the Strategy pattern.
Demerits
• The application must be aware of all the strategies to select the right one in right
situation.
• The memory requirement for implementing this pattern is more as Client has to maintain
the object of Strategy base clas, in order to choose appropriate algorithm each time.
Related Patterns
Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 20
• Strategy is based on Polymorphism
• Provides Protected Variations with respect to changing algorithms.
• Strategies are often created by a Factory.

OBSERVER/Publish-Subscribe/Delegation Event Model (GoF) -Behavioral Design Pattern

Observer pattern is used when there is one-to-many relationship between objects such as
if one object is modified, its dependent objects are to be notified automatically.
Problem
Different kinds of subscriber objects are interested in the state changes or events of a
publisher object, and want to react in their own unique way when the publisher generates an
event. Moreover, the publisher wants to maintain low coupling to the subscribers. What to do?
Solution
Define a "subscriber" or "listener" interface. Subscribers implement this (advice)
interface. The publisher can dynamically register subscribers who are interested in an event and
notify them when an event occurs.
The major ideas and steps in this example:
1. An interface is defined; in this case, PropertyListener with the operation
onPropertyEvent.
2. Define the window to implement the interface.
o SaleFrame1 will implement the method onPropertyEvent.
3. When the SaleFrame1 window is initialized, pass it the Sale instance from which it is
displaying the total.
4. TheSaleFrame1 window registers or subscribes to the Sale instance for notification of
"property events," via the addPropertyListener message. That is, when a property (such
as total) changes, the window wants to be notified.
5. Note that the Sale does not know about SaleFrame1 objects; rather, it only knows about
objects that implement the PropertyListener interface. This lowers the coupling of the
Sale to the window the coupling is only to an interface, not to a GUI class.
6. The Sale instance is thus a publisher of "property events." When the total changes, it
iterates across all subscribing PropertyListeners, notifying each.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 21
Why Is It Called Observer, Publish-Subscribe, or Delegation Event Model?
• Originally, this idiom was called publish-subscribe, and it is still widely known by that
name. One object "publishes events," such as the Sale publishing the "property event"
when the total changes. No object may be interested in this event, in which case, the Sale
has no registered subscribers. But objects that are interested "subscribe" or register to
interest in an event by asking the publishing to notify them.
• It has been called Observer because the listener or subscriber is observing the event.
• It has also been called the Delegation Event Model (in Java) because the publisher
delegates handling of events to "listeners"
Merits
• The pattern is useful when there is a change of state in one object that must be reflected
in another object.
• The new observers can be added easily with the minimal changes in the entire code.
• It allows to send data to many other objects in very efficient manner.
Demerits
• When there are several observables (subjects) and Observers then there are multiple
relations that need to be maintained. Due to which the overall code becomes complex.

BRIDGE (GoF) - Structural Design Pattern

• The Bridge design pattern separates or decouples the abstraction from implementation
without using inheritance.
• It allows the Abstraction and the Implementation to be developed independently and the
client code can access only the Abstraction part without being concerned about the
Implementation part.
• The abstraction is an interface or abstract class and the implementor is also an interface
or abstract class.
• The abstraction contains a reference to the implementor. Children of the abstraction are
referred to as refined abstractions, and children of the implementor are concrete
implementors. Since we can change the reference to the implementor in the abstraction,
we are able to change the abstraction’s implementor at run-time. Changes to the
implementor do not affect client code.
• It increases the loose coupling between class abstraction and it’s implementation.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 22
Elements of Bridge Design Pattern
• Abstraction – It defines the Abstraction interface. Contains a reference to the
implementor.
• RefinedAbstraction – Extends the abstraction takes the finer detail one level below. Hides
the finer elements from implementors.
• Implementor – It defines the interface for implementation classes.
• Concrete Implementation – This is a normal class which implements the implementor
interface.
Merits
• It separates implementation from interface
• It can be used when the class vary quite often.
• It is useful in graphic toolkits that need to run on multiple platforms.
• The implementation details can be effectively hidden from the client, so that the client
can focus on just the behavior desired from the abstraction.
Demerits
• Due to separation of interface and implementation, it increases complexity of the client
program.
• The performance of the overall code is decreased as the abstraction needs to pass
messages to the implementer for the operation to get executed.

Difference between Bridge and Adapter (AU Dec 2015 Marks 8)

Bridge Adapter
It is used to decouple an abstraction class from It is used when two incompatible interfaces
its implementation need to work together
It can be used when class vary quite often It is often used to make existing classes work
with other without modifying their source code
Merit: The implementation details can be Merit: If we have several modules
effectively hidden from the client, so that the implementing the same functionality and we
client can focus on just the behavior desired wrote adapters for them, the adapters are
from the abstraction. implementing the same interface.
Demerit: Due to separation of interface and Demerit: It makes the code complex and
implementation, it increases complexity of the difficult to debug.
client program.
UML Representation UML Representation

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 23
MAPPING DESIGNS TO CODE
Process: Write source code for
• Class and interface definitions
• Method definitions
Design Class Diagrams (DCD)
• DCDs contain class or interface names, classes, method and simple attributes.
• These are sufficient for basic class definitions.
• Elaborate from associations to add reference attributes.

Adding Reference Attributes


• An attribute that refers to another complex objects.
• Reference Attributes are suggested by associations and navigability in a class diagram.
• Example: A product specification reference on a Sales Line Item. So here we can use product
spec as a complex reference attribute to sales line item class.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 24
Reference Attributes and Role Names
Each end of an association is a role. Reference Attributes are often suggested by
role names. (Use role names as the names of reference attributes).

Creating methods from Interaction Diagrams


Interaction Diagrams are used to specify methods. They give most of the details for what
the method does.
The enterltem interaction diagram in Figure 20.6 illustrates the Java definition of the
enterltem method.

In this example, the Register class will be used. A Java definition is shown in Figure 20.7

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 25
Containers and Collections
• Where an object must maintain visibility to a group of other objects, such as a group of Sales
Line Items in a Sale, object-oriented languages often use an intermediate container or
collection.
• These will be suggested by a multiplicity value greater than one on a class diagram.

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 26
Working Example: PM (Project Management System)

PM: Use Case Diagram

PM: Class Diagram

PM: Class to Code


• class WorkPackage;
• class Project;
• class Activity;
• class Task;
• class WorkProduct;
• class Resource;

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 27
• class Skill;
• class ResourceXSkill;

PM: Class to Code


class WorkPackage
{ // Details omitted };
class Project : public WorkPackage
{ private: CollectionByVal<Activity> theActivity; };
class Activity : public WorkPackage
{ private: Project *theProject;
CollectionByVal<Task> theTask;
CollectionByRef<WorkProduct>
theWorkProduct; };

PM: DCD Mapping

PM: DCD Code

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 28
PM: Sequence Diagram

PM: Sequence to Main


Void main (void)
{ char *Name; char *Descr;
Date StartDate; Project aProject;
// provide project Name, descr, and startdate
aProject.setName (Name);
aProject.setDescr (Descr);
aProject.setStartDate (StartDate);
aProject.save () ;}

Prepared By: Dr.Adlin Sheeba, Dept. of CSE, St.Joseph’s Institute of Technology Page 29

You might also like