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

CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

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 – behavioral – Strategy – observer –Applying GoF design
patterns – Mapping design to code

4.1 GRASP: GENERAL RESPONSIBILITY ASSIGNMENT SOFTWARE


PATTERNS/PRINCIPLES

The GRASP patterns are a learning aid to help when one understands 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.

4.1.1 Responsibilities and Methods

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


 knowing about related objects
 knowing about things it can derive or calculate

Department of CSE Page 106


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.1.2 Responsibilities and Interaction Diagrams

Interaction diagrams show choices in assigning responsibilities to objects. When created,


decisions in responsibility assignment are made, which are reflected in what messages are sent to
different classes of objects. This chapter emphasizes fundamental principles expressed in the
GRASP pattern to guide choices in where to assign responsibilities. These choices are reflected
in interaction diagrams.

Figure 4.1 Responsibilities and methods are related.

4.2 PATTERNS

A pattern is a named description of a problem and solution that can be applied to new
contexts; ideally, it provides advice in how to apply it in varying circumstances, and considers
the forces and trade-offs. Many patterns provide guidance for how responsibilities should be
assigned to objects, given a specific category of problem.

The Gang of Four Pattern (GoF Patterns)

The 23 patterns, authored by four people Erich Gamma, Richard Helm, Ralph Johnson
and John Glissades are called the Gang of Four Patterns(GoF Patterns) design patterns.

Department of CSE Page 107


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.3 CREATOR
Mainly used to create an instance of a class.
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.
 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:

In the POS application, who should be responsible for creating a SalesLineltem instance?
By Creator, we should look for a class that aggregates, contains, and so on, SalesLineltem
instances. Consider the partial domain model given in Figure4.2

.
Figure 4.2 Partial domain model.

Department of CSE Page 108


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Since a Sate 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. This leads to a design of object interactions as shown in Figure 4.3.

Discussion: Creator guides assigning responsibilities related to the creation of objects, a very
common task. The basic intent of the Creator pattern is to find a creator that needs to be
connected to the created object in any event. Choosing it as the creator supports low coupling.

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.

Figure 4.3 Creating a SalesLineltem.

Benefits:

 Low coupling (described next) is supported,


 lower maintenance dependencies and
 higher opportunities for reuse.
 Increased clarity

Department of CSE Page 109


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Related Patterns or Principles:

 Low Coupling
 Concrete Factory
 Abstract factory
4.4 INFORMATION EXPERT (OR EXPERT)

Information Expert assigns responsibility to the class that has the information needed to
fulfill the responsibility.

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.

A Design Model may define hundreds or thousands of software classes, and an application may
require hundreds or thousands of responsibilities to be fulfilled. During object design, when the
interactions between objects are defined, we make choices about the assignment of
responsibilities to software classes. Done well, systems tend to be easier to understand, maintain,
and extend, and there is more opportunity to reuse components in future applications.

Example : In the NextGEN POS application, some class needs to know the grand total of a sale.

It is necessary to know about all the SalesLineltem instances of a sale and the sum of their
subtotals

Figure 4.4 Partial interaction and class diagrams.

In terms of an interaction diagram, this means that the Sale needs to send get-Subtotal messages
to each of the SalesLineltems and sum the results;

Department of CSE Page 110


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Figure 4.5 Calculating the Sale sub total

To fulfill the responsibility of knowing and answering its subtotal, a SalesLineltem 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.

Figure 4.6 Calculating the Sale sub total

Department of CSE Page 111


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

To fulfill the responsibility of knowing and answering the sale’s total, three responsibilities were
assigned to three design classes of objects as follows.

SI NO Design Class Responsibility


1 Sale knows sale total
2 SalesLineltem knows line item subtotal
3 ProductSpecification knows product price

Discussion: Information Expert is frequently used in the assignment of responsibilities; it is a


basic guiding principle used continuously in object design. Expert is not meant to be an obscure
or fancy idea; it expresses the common "intuition" that objects do things related to the
information they have.

Contraindications: There are situations where a solution suggested by Expert is undesirable,


usually because of problems in coupling and cohesion

Benefits:

 Information encapsulation is maintained, since objects use their own information to


fulfill tasks.
 supports low coupling, which leads to more robust and maintainable systems.
 encourage more cohesive "lightweight" class definitions that are easier to understand and
maintain.
 High cohesion is usually supported (another pattern discussed later).

Related Patterns or Principles:

 Low Coupling
 High cohesion
4.5 LOW COUPLING

Coupling is a measure of how strongly one element is connected to, has knowledge of, or
relies on other elements.

Department of CSE Page 112


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

An element with low (or weak) coupling is not dependent on too many other elements; "too
many" is context-dependent, but will be examined. These elements include classes, subsystems,
systems, and so on.

A class with high (or strong) coupling relies on many other classes. Such classes may be
undesirable;

Problem: How to support low dependency, low change impact, and increased reuse?.

Solution: Assign a responsibility so that coupling remains low.

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

payment Register Sale

Assume we have a need to create a Payment instance and associate it with the Sale.
What class should be responsible for this? Since a Register "records" a Payment in the real-world
domain, the Creator pattern suggests Register as a candidate for creating the Payment. The
Register instance could then send an addPayment message to the Sale, passing along the new
Payment as a parameter. A possible partial interaction diagram reflecting this is shown in Figure
4.7

Figure 4.7 Register creates Payment.

This assignment of responsibilities couples the Register class to knowledge of the Payment class.
UML notation: Note that the Payment instance is explicitly named p so that in message 2 it can

Department of CSE Page 113


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

be referenced as a parameter. An alternative solution to creating the Payment and associating it


with the Sale is shown in Figure 4.8

Figure 4.8 Sale creates Payment.

Discussion: Low Coupling is a principle to keep in mind during all design decisions; it is an
underlying goal to continually consider.

In object-oriented languages common forms of coupling from TypeX to TypeY include:

 Type X has an attribute (data member or instance variable) that refers to a Type Y
instance, or Type Y itself.
 A Type X object calls on services of a TypeY object.
 Type X has a method that references an instance of Type Y, or Type Y itself, by any
means.
 Type X is a direct or indirect subclass of Type Y.
 Type Y is an interface, and Type X implements that interface.

Contradictions:

High coupling to stable elements and to pervasive elements is seldom a problem.

Benefits

 not affected by changes in other components


 simple to understand in isolation
 convenient to reuse

Department of CSE Page 114


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 Related Patterns or Principles:


 Protected variation

4.6 HIGH COHESION

In terms of object design, 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. These elements include classes, subsystems, and so on.

A class with low cohesion does many unrelated things, or does too much work. Such classes are
undesirable;

Problem: How to keep complexity manageable?

Solution: Assign a responsibility so that cohesion remains high

Example: The same example problem used in the Low Coupling pattern can be analyzed for
High Cohesion. Assume we have a need to create a (cash) Payment instance and associate it with
the Sale. What class should be responsible for this? Since Register records a Payment in the real-
world domain. The Register instance could then send an addPayrnent message to the Sale,
passing along the new Payment as a parameter, as shown in Figure 4.9

Figure 4.9 Register creates Payment.

Department of CSE Page 115


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

The second design below delegates the payment creation responsibility to the Sale, and the
second design supports both high cohesion and low coupling, it is desirable.

Figure 4.10 Sale creates Payment

Discussion :Like Low Coupling, High Cohesion is a principle to keep in mind during all design
decisions; it is an underlying goal to continually consider. It is an evaluative principle that a
designer applies while evaluating all design decisions.

Here are some scenarios that illustrate varying degrees of functional cohesion:

 Very low cohesion -A class is solely responsible for many things in very dif ferent
functional areas.
 Low cohesion - A class has sole responsibility for a complex task in one func tional area.
 High cohesion - A class has moderate responsibilities in one functional area and
collaborates with other classes to fulfill tasks.
 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.
 Modular design – Modularity is the property of a system that has been decomposed into
a set of cohesive and loosely coupled modules.

Benefits:

Department of CSE Page 116


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 Clarity and ease of comprehension of the design is increased.


 Maintenance and enhancements are simplified.
 Low coupling is often supported.
highly related functionality is increased
4.7 CONTROLLER

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.

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.

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
<UseCaseName>Handler, <UseCaseName>Coordinator, or <Use-CaseName>Session (use-case
or session controller).

 Use the same controller class for all system events in the same use case scenario.
 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:

In the NextGen application, there are several system operations, as illustrated in Figure 4.11

Department of CSE Page 117


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Figure 4.11System operations associated with the system events.

Who should be the controller for system events such as enterltem and endSale.

Discussion: Systems receive external input events, typically involving a GUI operated by a
person. Other mediums of input include external messages such as in a call processing
telecommunications switch, or signals from sensors such as in process control systems.

Bloated Controllers :

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. This usually involves a violation of Information Expert and
High Cohesion.
 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.

There are several cures to a bloated controller, including:

1. Add more controllers - a system does not have to have only one .For example, consider
an application with many system events, such as an airline reservation system.

Department of CSE Page 118


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

2. Design the controller so that it primarily delegates the fulfillment of each system
operation responsibility on to other objects.

Figure 4.12 Controller for enterltem.

Benefits:

 Increased potential for reuse and pluggable interface


 Opportunity to reason about the state of the use case

Department of CSE Page 119


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Related Patterns

 Command—In a message-handling system, each message may be repre sented and


handled by a separate Command object
 Facade—A facade controller is a kind of Facade
 Layers—This is a POSA pattern. Placing domain logic in the domain layer rather than the
presentation layer is part of the Layer patterns
 Pure Fabrication— This is another GRASP pattern. A Pure Fabrication is an arbitrary
creation of the designer, not a software class whose name is inspired by the Domain
Model.
4.8 CREATIONAL PATTERN(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.

Also Known As: Virtual Constructor

Motivation:

 Frameworks use abstract classes to define and maintain relationships between objects.
 A framework is often responsible for creating these objects as well.
 Consider a framework for applications that can present multiple
documents to the user.
 Two key abstractions in this framework are the classes Application and Document.
 Both classes are abstract, and clients have to subclass them to
realize their application-specific implementations.

Applicability:

Use the Factory Method pattern when

 a class can't anticipate the class of objects it must create.

Department of CSE Page 120


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 a class wants its subclasses to specify the objects it creates.


 classes delegate responsibility to one of several helper subclasses

Structure:

Participants:

 Product (Document) – defines the interface of objects the factory method


creates.
 ConcreteProduct (MyDocument) – implements the Product interface.
 Creator (Application) - m declares the factory method, which returns an object of
type Product. Creator may also define a default implementation of the factory
method that returns a default ConcreteProduct object.
 ConcreteCreator (MyApplication) – m overrides the factory method to return an
instance of a ConcreteProduct.

Collaborations: Creator relies on its subclasses to define the factory method so that it returns an
instance of the appropriate ConcreteProduct.

Consequences:

 Factory methods eliminate the need to bind application specific


classes into your

Department of CSE Page 121


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 Subclassing is fine when the client has to subclass the Creator class.
 Provides hooks for subclasses
 Connects parallel class hierarchies

Implementation:

 Consider the issues when applying the Factory Method pattern:


 Two major varieties: The two main variations of the Factory Method pattern are

i)the case when the Creator class is an abstract class and does not provide an implementation
for the factory method it declares,

ii)the case when the Creator is a concrete class and provides a default implementation for the
factory method.

Issues

• Parameterized factory methods: The factory method


creates multiple kinds of products.
• The factory method takes a parameter that identifies the kind of object to create.
• All objects the factory method creates will share the Product interface
• A parameterized factory method has the following general
form, where MyProduct and YourProduct are subc creator

Class Creator
{
public:

virtual Product* Create(ProductId);

};

Product *Crteator::*Create(ProductId id);

Department of CSE Page 122


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

if (id == MINE) return new MyProduct

if (id == YOURS) return new YourProduct;

// repeat for remaining products...

return 0;

A subclass MyCreator could swap MyProduct and YourProduct and support a new TheirProduct
subclass:

Product* MyCreator::Create (ProductId id)

if (id == YOURS) return new MyProduct;

if (id == MINE) return new YourProduct;

// N.B.: switched YOURS and MINE

if (id == THEIRS) return new TheirProduct;

return Creator::Create(id); //called f all others fail

Parameterized factory methods:

 call Create on the parent class.

Department of CSE Page 123


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

That's because MyCreator::Create handles only YOURS, MINE, and THEIRS differently than
the parent class.

 It isn't interested in other classes.


 Hence MyCreator extends the kinds of products created, and it defers
responsibility for creating all but a few products to its parent.

Naming conventions:

For example, the MacApp Macintosh application framework always declares the
abstract operation that defines the factory method as Class* DoMakeClass(), where Class is the
Product class.

4.9 STRUCTURAL PATTERN (BRIDGE)

Intent: The Bridge pattern separates an object's abstraction from its implementation so that you
can vary them independently.

Also Known As:Handle/Body

There are 2 parts in Bridge design pattern:

1. Abstraction
2. Implementation

Motivation:

 The bridge pattern 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 implementer is also an interface or
abstract class.
 It increases the loose coupling between class abstraction and it’s implementation.

Participants:

Department of CSE Page 124


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 Abstraction – core of the bridge design pattern and defines the crux. Contains a reference to
the implementer.
 Refined Abstraction – Extends the abstraction takes the finer detail one level below. Hides
the finer elements from implementers.
 Implementer – It defines the interface for implementation classes. This interface does not
need to correspond directly to the abstraction interface and can be very different.
Abstraction imp provides an implementation in terms of operations provided by
Implementer interface.
 Concrete Implementation – Implements the above implementer by providing concrete
implementation.

Structor:

Collaborations:Abstraction forwards client request to its implementor object.

Consequences:

 Decoupling interface and implementation


 Improved extensibility
 Hiding implementation details from clients.

Department of CSE Page 125


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Implementation:

 In situations where there is only one implementations creating an abstract Implementer


class is not necessary.
 Creating the right implementer object –if abstraction knows about all
ConcreteImplementor classes then it can instantiate one of them in its constructor based
on the constructor parameter.

4.9 STRUCTURAL PATTERN (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.

Also Known As: Wrapper

Motivation:

Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
Adapter is responsible for functionality the adapted class does not provide.

Applicability:

 The existing class, and its interface does not match the one you need.
 to create a reusable class that cooperates with unrelated classes,
 An object adapter can adapt the interface of its parent class.

Structure:

Class Adapter (uses multiple interfaces to adapt)

Department of CSE Page 126


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Participants:

 Target - defines the domain-specific interface that Client


 Client - collaborates with objects conforming to the Target interface.
 Adaptee - defines an existing interface that needs adapting.
 Adapter - adapts the interface of Adaptee to the Target interface

Object Adapter (relies on object composition)

Collaborations: Clients call operations on an Adapter instance. In turn, the adapter calls Adaptee
operations that carry out the request

Consequences:

A class adapter

 won't work when we want to adapt a class and all its subclasses.

Department of CSE Page 127


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 lets Adapter override some of Adaptee's behavior, since Adapter is a subclass of


Adaptee.

An Object Adapter

 lets a single Adapter work with many Adaptees


 makes it harder to override Adaptee behavior

Implementation:In C++ implementation of a class adapter ,Adapter would inherit publicly from
Target and privately from Adaptee.

TextShape::TextShape (TextView* t)

_text = t;

void TextShape::BoundingBox ( Point& bottomLeft, Point& topRight)

Coord bottom, left, width, height;

bottomLeft = Point(bottom, left);

topRight = Point(bottom + height, left + width);

Bool TextShape::IsEmpty ()

return _text->IsEmpty();

Department of CSE Page 128


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Manipulator*
TextShape::CreateManipulator ()
const { return new
TextManipulator(this);

4.11 BEHAVIORAL PATTERN - STRATEGY

Intent:

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that use it.

Also known as: policy

Motivation:

Defining classes that encapsulate different line breaking algorithms. An


algorithm that's encapsulated in this way is called a strategy.

Applicability:

Use the Strategy pattern when

 many related classes differ only in their behavior.


 you need different variants of an algorithm.
 An algorithm uses data that clients shouldn't know about
 A class defines many behaviors, and these appear as multiple conditional
statements in its operations.

Participants:

 Strategy -declares an interface common to all supported algorithms.


 ConcreteStrategy - implements the algorithm using the Strategy interface

Department of CSE Page 129


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

 Context - maintains a reference to a Strategy object.

Collaborations:

 Strategy and Context interact to implement the chosen algorithm.


 A context may pass all data required by the algorithm to the strategy when the algorithm
is called.
 Alternatively, the context can pass itself as an argument to Strategy
operations.
 A context forwards requests from its clients to its strategy.

Structure:

Consequences:

 Families of related algorithms. Hierarchies of Strategy classes define a family of


algorithms or behaviors for contexts to reuse. Inheritance can help factor out common
functionality of the algorithms.
 An alternative to sub classing. Inheritance offers another way to support a variety of

Department of CSE Page 130


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

algorithms or behaviors.

4.12 APPLYING GOF PATTERN

GoF patterns are generally considered as the foundation of all other patterns. Design patterns
are recurring solutions to software design problems.

4.12.1 Adapter (GoF)

Adapter pattern is used to convert the programming interface of one class into that of
another. The concept is simple: write a class that has the desired interface and then make it
communicate with the class that has a different interface.

Context / 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.

Figure 4.13 Using an Adapter.

Department of CSE Page 131


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.12.2 Singleton (GoF)

Sigleton pattern is used to implement the mathematical concept of a singleton,by restricting


the instantiation of a class to one object.

Singleton is a class which only allows a single instance of itself to be created and
gives simple access to that instance.

Context / 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.

Figure4.14 Implicit getlnstance Singleton pattern message indicated in the UML with a
stereotype.

4.12.3 Factory (GoF)

Factory pattern is a design pattern to implement the concept of factories. This pattern is a
GoF abstract factory pattern. It is also called as simple factory or concrete factory. Factory
objects have several advantages:

• Separate the responsibility of complex creation into cohesive helper objects.

• Hide potentially complex creation logic.

Department of CSE Page 132


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

• Allow introduction of performance-enhancing memory management strategies, such as


object caching or recycling.

Context / 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.

Figure 4.15 The Factory pattern.

4.12.4 Strategy (GoF)

The next design problem to be resolved is to provide more complex pricing logic, such as a
store-wide discount for the day, senior citizen discounts, and so forth.

Context / 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.

Department of CSE Page 133


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

In this example, the context object is a Sale. When a getTotal message is sent to a Sale, it
delegates some of the work to its strategy object.

Figure 4.16 Strategy in collaboration.

4.12.5 Observer

In observer pattern, an object called the subject maintains a list of its dependents, called
observers, and notifies them automatically of any state changes by calling one of their
methods.

Problem: different kinds of subscriber objects are interested in the state changes or events of
a publisher object.

Solution: Define a subscriber or listener interface. Subscriber implement this interface .the
publisher can dynamically register subscriber who are interested in an event and notify them
when an event occurs.

4.13. MAPPING DESIGNS TO CODE

Map design artifacts to code in an object oriented language. Implementation in an object-


oriented programming language requires writing source code for:

• class and interface definitions

• method definitions

Department of CSE Page 134


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.13.1 Creating Class Definitions from DCDs

At the very least, DCDs depict the class or interface name, super classes, method signatures,
and simple attributes of a class. This is sufficient to create a basic class definition in an
object-oriented programming language.

Figure 4.17 SalesLineItem in Java.

4.13.2 Adding Reference Attributes

A reference attribute is an attribute that refers to another complex object, not to a primitive
type such as a String, Number, and so on.

Figure 4.18 Adding reference attributes.

Department of CSE Page 135


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.13.3 Role Names

The next iteration will explore the concept of role names in static structure diagrams.
Each end of an association is called a role. Briefly, a role name is a name that identifies the
role and often provides some semantic context as to the nature of the role. Each end of an
association is a role, which has various properties, such as:

 Name
 multiplicity

Figure 4.19 Role names may be used to generate instance variable names

Department of CSE Page 136


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.13.4 Creating Methods from Interaction Diagrams

The sequence of these messages translates to a series of statements in the method definition.

Figure 4.20The enterltem interaction diagram.

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

public void enterltem ( ItemID itemID, int qty)

Message 1: A getSpecification message is sent to the ProductCatalog to retrieve a


ProductSpecification.

ProductSpecif ication spec = catalog. getSpecif ication( itemID );

Message 2: The makeLineltem message is sent to the Sale. sale .

makeLineltemf spec, qty);

Department of CSE Page 137


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

4.13.5 Order of Implementation

Classes need to be implemented from least-coupled to most-coupled.

Figure 4.21Possible order of class implementation and testing.

4.13.6 Test Driven or Test-First Programming

In Test Driven Development(TDD) , write a little test code, then write a little production
code, make it pass the test, then write some more test code, and so forth.

Advantages include:

• The unit tests actually get written—Human (or at least programmer) nature is such that
avoidance of writing unit tests is very common, if left as an afterthought.

• Programmer satisfaction—If a developer writes the production code, informally debugs it,
and then as an afterthought adds unit tests, it does not feel very satisfying

• Clarification of interface and behavior—By writing the unit test for it first, one clarifies the

Department of CSE Page 138


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

design of the class.

• Provable verification— having hundreds or thousands of unit tests provides some


meaningful verification of correctness.

• The confidence to change things—When a developer needs to change existing code—


written by themselves or others—there is a unit test suite that can be run, providing
immediate feedback if the change caused an error.

4.13.7 Summary of Mapping Designs to Code

Introduction to the Program Solution

This section presents a sample domain object layer program solution in Java for this
iteration. The code generation is largely derived from the design class diagrams and
interaction diagrams defined in the design work, based on the principles of mapping designs
to code as previously explored.

Class Payment

public class Payment


{
private Money amount;
public Payment( Money cashTendered )
{
amount = cashTendered;
}
public Money getAmount()
{
return amount;
}
}
Class ProductCatalog

Department of CSE Page 139


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

public class ProductCatalog


{
private Map productSpecifications = new HashMap();
public ProductCatalog()
{
// sample data
ItemID idl = new
ItemID( 100 ); ItemID id2 = new ItemID( 200 );
Money price = new Money( 3 );
ProductSpecification ps; ps = new ProductSpecification( idl, price, "product 1" );
productSpecifications.put( idl, ps );
ps = new ProductSpecification( id2, price, "product 2" );
ProductSpecifications.put( id2, ps );
}
public ProductSpecification getSpecification( ItemID id )
{
return (ProductSpecification)productSpecifications.get( id ); }
}
}
Class Register
public class Register
{
private ProductCatalog catalog;
private Sale sale; public Register( ProductCatalog catalog )
{
this.catalog = catalog;
}
public void endSaleO { sale.becomeComplete();
}
public void enterltem( ItemID id, int quantity )
{

Department of CSE Page 140


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

ProductSpecification spec = catalog.getSpecification( id );


sale.makeLineItem( spec, quantity ); }
public void makeNewSale()
{
sale = new Sale();
}
public void makePayment( Money cashTendered ) { sale.makePayment( cashTendered );
}
}
Class ProductSpecification
public class ProductSpecification
{
private ItemID id;
private Money price;
private String description;
public ProductSpecification ( ItemID id. Money price. String description )
{
this.id = id;
this.price = price;
this.description = description;
}
public ItemID getltemlDO
{
return id;
}
public Money getPrice()
{
return price;
}
public String getDescription()
{

Department of CSE Page 141


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

return description;
}
}
Class Sale
public class Sale
{
private List lineltems = new ArrayListO;
private Date date = new Date();
private boolean isComplete = false;
private Payment payment;
public Money getBalanceO
{
return payment.getAmount().minus( getTotal() );
}
public void becomeComplete()
{
isComplete = true;
}
public boolean isComplete()
{
return isComplete;
}
public void makeLineltem ( ProductSpecification spec, int quantity )
{
lineltems.add( new SalesLineltem( spec, quantity ) );
}
public Money getTotal()
{ Money total = new MoneyO; Iterator i = lineltems.iterator( ) ;
while ( i.hasNextO )
{
SalesLineltem sli = (SalesLineltem) i.nextO;

Department of CSE Page 142


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

total.add( sli.getSubtotal() );
}
return total;

POSSIBLE TWO MARKS

1.Distinguish between coupling and cohesion.

Cohesion Coupling
1 Cohesion refers to what the class (or It refers to how related are two classes /
module) modules and how dependent they are on each
other. Being low coupling would mean that
will do. Low cohesion would mean that the
changing something major in one class should
class does a great variety of actions and is
not affect the other. High coupling would
not focused on what it should do. High
make your code difficult to make changes as
cohesion would then mean that the class is
well as to maintain it, as classes are coupled
focused on what it should be doing, i.e. only
closely together, making a change could mean
methods relating to the intention of the class
an entire system revamp

2 High cohesion within modules Low coupling betweenmodules.

3 Increased cohesion and decreased coupling The most effective method of decreasing
do
coupling and increasing cohesion is
leads to good software design.
design by interface

2. List the steps involved in mapping design to code.

The steps involved in mapping design to code are,

Department of CSE Page 143


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

1. Class and interface definitions

The required visibility and associations between classes are indicated by the interaction

diagrams.

2. Method definitions

A method body implementation may be shown in a UML note box. It should be placed

within braces, it is semantic influence. The syntax may be pseudo-code, or any language 3.
3.Mention the Interface and Domain Layer Responsibilities.

The UI layer should not have any domain logic responsibilities. It should only be responsible
for user interface tasks, such as updating widgets. The UI layer should forward requests for all
domain-oriented tasks on to the domain layer, which is responsible for handling them.

4. Define patterns.

A pattern is a named problem/solution pair that can be applied in new context, with advice on
how to apply it in novel situations and discussion of its trade-offs.

5. List out GRASP Patterns?

 Information Expert .
 Creator .
 High Cohesion .
 Low Coupling .
 Controller

6. What is meant by responsibilities? List the types of responsibilities.

The UML defines a responsibility as “a contract or obligation of a classifier”.


Responsibilities

Department of CSE Page 144


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

Are related to the obligations or behavior of an object in terms of its role. The responsibilities are
of the following two types: doing and knowing.

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

• knowing about related objects

• knowing about things it can derive or calculate

7. Who is creator?

Solution Assign class B the responsibility to create an instance of class A if one or more of the
following is true:

 B aggregates an object.
 B contains an object.
 B records instances of objects.
 B closely uses 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 an object.
 If more than one option applies, prefer a class B which aggregates or contains
class A.

Department of CSE Page 145


CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

8. List out some scenarios that illustrate varying degrees of functional cohesion

 Very low cohesion


 low cohesion
 High cohesion
 Moderate cohesion

9. Define Modular Design.

Coupling and cohesion are old principles in software design; designing with objects does not
imply ignoring well-established fundamentals. Another of these. Which is strongly related to
coupling and cohesion? is to promote modular design.

10. What are the advantages of Factory objects?

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

11. Designing for Non-Functional or Quality Requirements.

Interestingly—and this a key point in software architecture—it is common that the large-scale
themes, patterns, and structures of the software architecture are shaped by the designs to
resolve the non-functional or quality requirements, rather than the basic business logic.

12. What is meant by Abstract Class Abstract Factory?

A common variation on Abstract Factory is to create an abstract class factory that is accessed
using the Singleton pattern, reads from a system property to decide which of its subclass
factories to create, and then returns the appropriate subclass instance. This is used, for example,
in the Java libraries with the java.awt.Toolkit class, which is an abstract class abstract factory
for creating families of GUI widgets for different operating system and GUI subsystems.
Department of CSE Page 146
CS8592/OBJECT ORIENTED ANALYSIS AND DESIGN

14. What is meant by Fine-Grained Classes?

Consider the creation of the Credit Card, Driver’s License, and Check software objects. Our
first impulse might be to record the data they hold simply in their related payment classes, and
eliminate such fine-grained classes. However, it is usually a more profitable strategy to use
them; they often end up providing useful behavior and being reusable.

15. Define coupling. APIRAL/MAY-2011

The degree to which components depend on one another. There are two types of
coupling, "tight" and "loose". Loose coupling is desirable for good software engineering but
tight coupling may be necessary for maximum performance. Coupling is increased when the
data exchanged between components becomes larger or more complex.

PART B QUESTIONS

1.What is GRASP? Explain the GRASP patterns creator, Information Expert, low coupling,
High cohesion?

2.Explain in detail about Adaptor, singleton, Factory.

3.Explain GRASP: designing objects with responsibilities.

PART C QUESTIONS

1.Compare cohesion and coupling with suitable examples?

2.How will you design behavioral pattern?

Department of CSE Page 147

You might also like