0% found this document useful (0 votes)
4 views24 pages

UNIT IV

The document discusses GRASP (General Responsibility Assignment Software Patterns), which provides principles for assigning responsibilities in object-oriented design. It outlines nine GRASP patterns, including Creator, Controller, Information Expert, Low Coupling, and High Cohesion, emphasizing the importance of these principles in creating maintainable and reusable software. Additionally, it introduces GoF design patterns, such as Adapter and Singleton, which help solve common design problems in software development.

Uploaded by

kanmaniapit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

UNIT IV

The document discusses GRASP (General Responsibility Assignment Software Patterns), which provides principles for assigning responsibilities in object-oriented design. It outlines nine GRASP patterns, including Creator, Controller, Information Expert, Low Coupling, and High Cohesion, emphasizing the importance of these principles in creating maintainable and reusable software. Additionally, it introduces GoF design patterns, such as Adapter and Singleton, which help solve common design problems in software development.

Uploaded by

kanmaniapit
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

UNIT IV

GRASP: Designing objects with responsibilities – Creator – Information expert – Low


Coupling –Controller – High Cohesion – Designing for visibility - Applying GoF design
patterns – adapter, singleton, factory and observer patterns

GRASP: DESIGNING OBJECTS WITH RESPONSIBILITIES


An introduction to object design in a easily understandable way.
GRASP stands for General Responsibility Assignment Software Patterns
􀂄 These are not ‘design patterns’, rather fundamental principles of object design
􀂄 GRASP patterns focus on one of the most important aspects of object design, assigning
responsibilities to classes.
􀂄 GRASP patterns do not address architectural design
What is object design?
􀁻 In the analysis part of the current and previous iterations you have
􀂄 Identified use cases and created use case descriptions to get the requirements
􀂄 Created and refined the domain concept model
􀂄 Assign methods to software classes
􀂄 Design how the classes collaborate (i.e. send messages) in order to fulfill the
functionality stated in the use cases.
What are responsibilities?
Responsibilities are related to the problem domain
􀂄 In design model, responsibilities are obligations of an object in terms of its behavior.
􀂄 There are two main types of responsibilities:
􀂄 Doing responsibilities:
􀁻 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
􀁻 Knowing about private encapsulated data
􀁻 Knowing about related objects.
􀁻 Knowing about things it can derive or calculate.
Example
􀁻 The Sale class might define methods to know its total; say, a method named getTotal.
􀁻 The Sale may collaborate with other objects, such as sending a getSubtotal message to
each SalesLineltem object asking for its subtotal.
GRASP –learning and doing Basic Design
The GRASP patterns are a learning aid to help one understand essential object design.
􀂄 Design reasoning is applied in a methodical, rational, explainable way.
􀂄 GRASP approach is based on assigning responsibilities, thus creating the basic object
and control structures
Nine GRASP patterns Nine GRASP patterns
• There are 9 GRASP patterns
– Creator
– Controller
– Information Expert
– High Cohesion
– Low Coupling
– Pure Fabrication
– Indirection
– Polymorphism
– Protected variations
Creator
Creation of objects is one of the most common activities in an object-oriented system.
Which class is responsible for creating objects is a fundamental property of the
relationship between objects of particular classes. Simply "Creator pattern is responsible
for creating an object of class".
In general, a class B should be responsible for creating instances of class A if one, or
preferably more, of the following apply:
 Instances of B contains or compositely aggregates instances of A
 Instances of B record instances of A
 Instances of B closely use instances of A
 Instances of B have the initializing information for instances of A and pass it on
creation.

← Problem: Who should be responsible for creating a new instance of some class ?
← The creation of objects is one of the most common activities in an object-oriented system.

← Consequently, it is useful to have a general principle for assignment of creation


responsibilities.

← Assigned well, the design can support low coupling, increased clarity, encapsulation, and
reusability.

← 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

← B is a creator of A objects.

← POS Example

← Who should be responsible for creating a SalesLineItem instance?

Figure 10.7. Partial Sale Domain Model

← Creating a SalesLineItem

Figure 10.8. Creating a SalesLineItem


← Discussion
← Creator guides assigning responsibilities related to 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.

← Aggregator aggregates Part

← Container contains Content

← Recorder records.

← Sometimes a creator is found by looking for the class that has the initializing data
that will be passed in during creation.

← 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

← In these instances, another pattern principle might be preferred

Information Expert
Information Expert is a principle used to determine where to delegate responsibilities.
These responsibilities include methods, computed fields and so on.
Using the principle of Information Expert a general approach to assigning responsibilities
is to look at a given responsibility, determine the information needed to fulfill it, and then
determine where that information is stored.
Information Expert will lead to placing the responsibility on the class with the most
information required to fulfill it

Controller
The Controller pattern assigns the responsibility of dealing with system events to a non-
UI class that represent the overall system or a use case scenario. A Controller object is a
non-user interface object responsible for receiving or handling a system event.

A use case controller should be used to deal with all system events of a use case, and may
be used for more than one use case (for instance, for use cases Create User and Delete
User, one can have one UserController, instead of two separate use case controllers).

It is defined as the first object beyond the UI layer that receives and coordinates
("controls") a system operation. The controller should delegate to other objects the work
that needs to be done; it coordinates or controls the activity. It should not do much work
itself. The GRASP Controller can be thought of as being a part of the Application/Service
layer (assuming that the application has made an explicit distinction between the
Application/Service layer and the Domain layer) in an object-oriented system with
common layers.

← Discussion
← Information Expert is a basic guiding principle used continuously in object
design.

← Expert is not meant to be obscure or fancy idea; it expresses the common


“intuition” that objects do things related to information they have.

← Fulfillment of a responsibility often requires information that is spread across


different classes of objects.

← Whenever information is spread across different objects , they will need to


interact via messages to share the work.

← Contraindications

← There are situations where the solution suggested by expert is undesirable,


usually because of problems in coupling and cohesion.

← Keep the application logic in one place, database in another place and so forth,
rather than intermingling different system concerns in the same component.

← Benefits
← Information encapsulation is maintained, since objects use their own information
to fulfill [Link] usually supports low coupling, which leads to more robust
and maintainable systems.

← Behavior is distributed across the classes that have the required information,
encouraging more cohesive “lightweight” class definitions that are easier to
understand and maintain.

← High cohesion is usually supported.

LOW COUPLING

← Coupling is a measure of how strongly one element is connected to, has


knowledge of, or relies on other element.
← Problem:

← How to support a low dependency, low change impact, and increased


reuse?
← Solution:
← Assign a responsibility so that coupling remains low.
← POS Example
← Assume we have a need to create a Payment instance and associate it with
the Sale.
← What class should be responsible for this?

Figure 10.9. POS Example Classes

Figure 10.10. Is It a Good Solution?

Figure 10.11. A better solution: Sale create Payment


← In practice, the level of coupling alone can’t be considered in isolation from other
principles such as Expert and High Cohesion. Nevertheless, it is one factor to
consider in improving a design.
← Discussion

← Low Coupling is a principle to keep in mind during all design decisions; it


is an underlying goal to continually consider. It is evaluative principle that
a designer applies while evaluating all design decisions.
← Common forms of coupling from X to Y (pp. 230)
← Low Coupling encourages assigning a a responsibility so that its
placement does not increase the coupling to such a level that it leads to the
negative results that high coupling can produce.
← There is no absolute measure of when coupling is too high. What is
important is that a developer can gauge the current degree of coupling, and
assess if increasing it will lead to problems.
← Contraindications
← High coupling to stable elements and to pervasive elements is seldom a
problem.
← Benefits
← Objects are not affected by changes in other components
← Objects are simple to understand in isolation
← Objects are convenient to reuse
HIGH COHESION
← Cohesion is a measure of how strongly related and focused are the responsibilities
of an element.
← High Cohesion: An element with highly related responsibilities, and which does
not do a tremendous amount of work, has high cohesion.
← Problem:
← How can complexity be kept manageable?
← Solution:
← Assign responsibility so that cohesion remains high.
← POS Example
← Assume we have a need to create a Payment instance and associate it with
the Sale.
← What class should be responsible for this?

Figure 10.12. POS Domain Classes

Figure 10.13. Is it a good Solution?

Figure 10.14. High Cohesion and Low Coupling


← In practice, the level of cohesion alone can’t be considered in isolation from other
responsibilities and other principles such as Expert and Low Coupling.
← Discussion

← Like Low Coupling, High Cohesion is a principle to keep in mind during


all design decisions; it is an underlying goal to consider constantly.
← Cohesion examples
← Some scenarios illustrating varying degrees of varying degrees of
functional cohesion:
← Very Low Cohesion – A class is solely responsible for many different
functional areas.
← Low Cohesion – A class has sole responsibility for a complex task in one
functional area.
← Moderate Cohesion – A class has light weight and sole responsibilities in a
few different areas that are logically related to the class concept, but not to
each other.
← High Cohesion – A class has moderate responsibilities in one functional
area and collaborates with other classes to fulfill tasks.
← Contraindications
← Grouping of responsibilities or code into one class or component to
simplify maintenance by one person. (Such grouping may also make
maintenance much more difficult.)
← Distributed server objects.
← It is sometimes desirable to create fewer and larger, less cohesive
server objects that provide an interface for many operations, due to
overhead and performance needs associated with remote objects
and remote communication.
← Benefits
← Clarity and ease of comprehension of design is increased.
← Maintenance and enhancements are simplified
← Low coupling is often supported

CONTROLLER PATTERN

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


event. It defines methods for system operation.
← Problem :

← Who should be responsible for handling an input system event?

← Solution

← Assign the responsibility for receiving or handling a system event message to a


class representing one of the following choices:

← Represent the overall system, device, or subsystem

← Represents a use case scenario within which the system event occurs

← POS Example

← Who should be controller for system events such as enterItem and endSale?

Figure 10.15. System Operations

Figure 10.16. Controller for enterItem?


Figure 10.17. Possible Controllers

← Discussion
← Controller pattern provides guidance for generally accepted, suitable choices.

← It is often desirable to use the same controller class for all the system events of
one use case so that it is possible to maintain information about the state of the
use case in the controller.

← Facade Controller

← 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 message processing system.

← Use–Case controller

← When placing the responsibilities in a façade controller leads to design with low
cohesion or high coupling, Use Case Controller is preferred as an alternative.

← When there are many system events across different processes;it factors their
handling into manageable separate classes.

← Benefits
← Increased potential for reuse,and pluggable interfaces.

← Provides information about the state of a use case.

← Bloated Controllers

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

← Solution to bloated controllers

← Add more controllers

← Design the controller so that it primarily delegates the fulfillment of each


system operation responsibility on to other objects.

Figure 10.18. Allocation of System Operations


← Interface Layer does not handle system events

Figure 10.19. Disirable Coupling of interface layer to domain layer

Figure 10.20. Less Desirable Coupling of interface layer to domain layer


DESIGNING FOR VISIBILITY - APPLYING GOF DESIGN PATTERNS

← What is Design Pattern?


← "Each pattern describes a problem which occurs over and over again in our
environment, and then describes the core of the solution to that problem, in such
a way that you can use the this solution a million times over, without ever doing
it the same twice."

← Christopher Alexander

← Patterns in software were popularized by the book Design Patterns: Elements of


Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph
Johnson, John Vlissides (also known ad the Gang of Four, or GoF)

← "Each pattern is a three-part rule, which expresses a relation between a certain


context, a problem, and a solution."

← Christopher Alexander

← "A design pattern describes a commonly-recurring structure of communicating


components that solves a general design problem within a particular context."

← GoF

← Common Partern Categories

← Creational Patterns

← These concern the process of object creation.

 AbstractFactory Pattern

 Builder Pattern

 FactoryMethod Pattern

 Prototype Pattern

 Singleton Pattern

← Structural Patterns patterns

← These deal with the composition of classes or objects.

 Adapter Pattern

 Bridge Pattern

 Composite Pattern
 Decorator Pattern

 Facade Pattern

 Flyweight Pattern

 Proxy Pattern

← Behacioral Patterns

← These characterize the ways in which classes or objects interact and


distribute responsibility.

 Chain Of Responsibility

 Command Pattern

 Interpreter Pattern

 Iterator Pattern

 Mediator Pattern

 Memento Pattern

 Observer Pattern

 State Pattern

 Strategy Pattern

 Template Method Pattern

 Visitor Pattern

ADAPTER PATTERN

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.

Example: Different Tax Calculators


Figure 15.1. The Adapter Pattern

← Using an Adaptor

Figure 15.2. Using An Adaptor


← The adapter pattern can be viewed as a specialization of some
GRASP building blocks
← Adapter supports Protected Vaeiations with respect to
changing external interfaces or third-party packages
through the use of an Indirection object that applies
interfaces and Polymorphism.

← There are hundreds of published patterns , however, most design


patterns can be seen as specializations of a few basic GRASP
principles.

← Example: Adapter and GRASP

Figure 15.3. Relating Adapter to some core GRASP


principles

FACTORY PATTERN

← Problem:
← Who should be responsible for creating objects when there
are special considerations, such as complex logic,a desire
to separate the creation responsibilities for better
cohesion, and so forth

← Who should responsible for the creating of the


adapters? Create which one?
← If some domain object creates them, the
responsibilities of the domain object are going
beyond pure application logic and into other
concerns related to connectivity with external
software components.

← Solution:

← Create a Pure Fabrication object called a Factory that


handles the creation

← Example:

← Figure 15.4. Factory Pattern

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

← Data-driven design
← Read in the class name from an external source (for
example, via a system property if Java is used) and then
dynamically loading the class.

SINGLETON PATTERN

The Factory raises a new problem in the design:


← Who creates the factory itself?

← How is it accessed?

Only one instance of the factory is needed within the process

The methods of this factory may need to be called from various


places in the code. (visibility)
One solution is pass the Factory instance around as a parameter
to wherever a visibility need is discovered for it, or to initialize
the objects that need visibility to it,with a permanent reference.

Alternative is Singleton pattern.

Problem:

← Exactly one instance of a class is allowed – it is a


“singleton”. Objects need global and single point of access.

Solution:

← Define a static method of the class that returns the


singleton.

← With this approach, a developer has global visibility


to this single instance,via the static getInstance
method of the class.

← Figure 15.5. Singleton Pattern


← Visibility to Single Instance

public class Register


{
public void initialize()
{
//… do some work…
//accessing the singleton Factory via the getInstance call
AccountingAdapter =
[Link]().getAccountingAdapter();
//…do some work…
}

//other methods…
}
← UML Shorthand for Singleton Access in Interaction Diagrams
← Add a <<singleton>> stereotype to the instance

Figure 15.6. Singleton in Interaction Diagram


← Lazy Initialization
← Reasons to prefer lazy Initialization

← Creation work is avoided, if the instance is never


actually accessed.
← The getInstance lazy initialization sometimes contains complex and
conditional creation logic.

public static synchronized ServiceFactory getInstance()


{
if(instance==null)
{
//critical section if multithreaded application
instance = new ServicesFactory();
}

return instance;
}
← Eager Initialization

public class ServiceFactory


{
//eager initialization

private static ServicesFactory instnace = new


ServicesFactory();

public static servicesFactory getInstance()


{
return instance;
}

//other methods…
}
← Preferred Methods
← Why not make all the service methods static methods of
the class itself, instead of using an instance object with
instance-side methods?
← How about add a static method called
getAccountingAdapter to ServiceFactory?

← Instance-side methods permit subclassing and


refinement of the singleton class into subclasses;
Static methods are not polymorphic and don’t permit
overriding in subclasses in most languages.

← Most object-oriented remote communication


mechanisms only support remote-enabling of
instance methods,not static methods.

← A class is not always a singleton in all application


contexts.

← Conclusion of External services with varying Interfaces Problem

Figure 15.7. Conclusion of External services with varying


Interfaces Problem

You might also like