Professional Documents
Culture Documents
6.unit 4
6.unit 4
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.
Knowing
doing
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 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.
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.
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.
Benefits:
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.
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
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;
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.
To fulfill the responsibility of knowing and answering the sale’s total, three responsibilities were
assigned to three design classes of objects as follows.
Benefits:
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.
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?.
Example: Consider the following partial class diagram from a NextGen case study:
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
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
Discussion: Low Coupling is a principle to keep in mind during all design decisions; it is an
underlying goal to continually consider.
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:
Benefits
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;
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
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.
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:
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 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
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.
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.
2. Design the controller so that it primarily delegates the fulfillment of each system
operation responsibility on to other objects.
Benefits:
Related Patterns
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.
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:
Structure:
Participants:
Collaborations: Creator relies on its subclasses to define the factory method so that it returns an
instance of the appropriate ConcreteProduct.
Consequences:
Subclassing is fine when the client has to subclass the Creator class.
Provides hooks for subclasses
Connects parallel class hierarchies
Implementation:
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
Class Creator
{
public:
};
return 0;
A subclass MyCreator could swap MyProduct and YourProduct and support a new TheirProduct
subclass:
That's because MyCreator::Create handles only YOURS, MINE, and THEIRS differently than
the parent class.
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.
Intent: The Bridge pattern separates an object's abstraction from its implementation so that you
can vary them independently.
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:
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:
Consequences:
Implementation:
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.
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:
Participants:
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.
An Object Adapter
Implementation:In C++ implementation of a class adapter ,Adapter would inherit publicly from
Target and privately from Adaptee.
TextShape::TextShape (TextView* t)
_text = t;
Bool TextShape::IsEmpty ()
return _text->IsEmpty();
Manipulator*
TextShape::CreateManipulator ()
const { return new
TextManipulator(this);
Intent:
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy
lets the algorithm vary independently from clients that use it.
Motivation:
Applicability:
Participants:
Collaborations:
Structure:
Consequences:
algorithms or behaviors.
GoF patterns are generally considered as the foundation of all other patterns. Design patterns
are recurring solutions to software design problems.
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.
Solution :Convert the original interface of a component into another interface, through an
intermediate adapter object.
Singleton is a class which only allows a single instance of itself to be created and
gives simple access to that instance.
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.
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:
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.
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?
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.
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.
• method definitions
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.
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.
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
The sequence of these messages translates to a series of statements in the method definition.
The enterltem message is sent to a Register instance; therefore, the enterltem method is
defined in class Register.
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
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
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;
total.add( sli.getSubtotal() );
}
return total;
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
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
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.
Information Expert .
Creator .
High Cohesion .
Low Coupling .
Controller
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.
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.
8. List out some scenarios that illustrate varying degrees of functional cohesion
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.
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.
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
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.
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?
PART C QUESTIONS