0% found this document useful (0 votes)
10 views17 pages

UNIT4

The document discusses GRASP (General Responsibility Assignment Software Patterns) principles for assigning responsibilities in object-oriented design, including concepts like Creator, Information Expert, Low Coupling, High Cohesion, and Controller. It also covers the Gang of Four (GoF) design patterns such as Factory, Singleton, Adapter, and Observer patterns, detailing their problems, solutions, and implementations. Additionally, the document explains the mapping of design to code in object-oriented languages and provides insights into the Bridge and Strategy patterns.

Uploaded by

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

UNIT4

The document discusses GRASP (General Responsibility Assignment Software Patterns) principles for assigning responsibilities in object-oriented design, including concepts like Creator, Information Expert, Low Coupling, High Cohesion, and Controller. It also covers the Gang of Four (GoF) design patterns such as Factory, Singleton, Adapter, and Observer patterns, detailing their problems, solutions, and implementations. Additionally, the document explains the mapping of design to code in object-oriented languages and provides insights into the Bridge and Strategy patterns.

Uploaded by

vedaraj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

UNIT IV

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

Explain in detail about GRASP design patterns.

GRASP

 General Responsibility Assignment Software Patterns (or Principles) consists of guidelines


for assigning responsibility to classes and objects in object- oriented design.
 Pattern is a named description of a problem and solution that can be applied to new contexts;
ideally a pattern advises us on how to apply its solution in varying circumstances.

The different patterns and principles used in GRASP are

 Creator
 Information expert
 Low Coupling
 High Cohesion
 Controller.
1.Creator:
Creation of objects is one of the most common activities in an object-oriented system.

Problem
Who should create an instance of a new class?

Solution
If B is a creator of A objects then atleast one of the following must be true.
• B contains A
• B compositely aggregates A
• B records A
• B closely uses A

Example
In the POS application, who should be responsible for creating a SalesLineltem instance? Consider the
partial domain model of SaleLineItem. Here Sale takes the responsibility of creating SalesLineItem
instance. Since sale contains many SalesLineItem objects.
The common task of creator is to assign responsibilities related to the creation of objects.
All common relationships between classes are
 Composite aggregates part
 Container contains content
 Recorder records
Benefits
 Lower maintenance due to low coupling
 Higher opportunities for reuse.

2.Information expert
Information Expert is a principle used to determine where to delegate responsibilities. These
responsibilities include methods, computed fields and so on.

Problem
What is a general principle of assigning responsibilities to objects?
Solution
Assign the responsibilities to information expert.

Example
In the NextGEN POS application, some class needs to know the grand total of a sale. Consider the partial
Domain Model.

Software class sale is added with the responsibility of getting total with the method getTotal
To determine lineitem sub total we need,
SalesLineitem.quantity’
ProductDescription.price
therefore, by Expert, SalesLineltem should determine the subtotal; it is the information expert. In terms of
an interaction diagram, this means that the Sale needs to send getSubtotal messages to each of the
SalesLineltems and sum the results.

After knowing and answering subtotal, a SalesLineItem has to know product price. ProductDescription is
an information expert for answering price.

Finally, three design classes, assigned with three responsibilities to find sales total.
3.Low Coupling

Coupling
Coupling is the measure of how strongly one element is connected to the other elements.

Types of coupling
There are 2 types of coupling
1) Low coupling or weak coupling
2) High coupling or strong coupling.

Low coupling
An element if does not depend on too many other elements like classes, subsystems and so on.

High coupling
A class with high coupling relies on many other classes.
The problems of high coupling are
 Forced local changes
 Harder to understand
 Harder to reuse

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:

Design 1:
Suggested by creator
1) Register instance send addpayment message to sale, passing newPayment as a parameter.
2) Register class couples with payment class and creates payment.
Design 2:
Suggested by low coupling
1) Here sale does the creation of payment.
2) It does not increase coupling and hence preferred.

Benefits
 Not affected by changes in other components
 Simple to understand in isolation
 Convenient to reuse

4.High Cohesion
Cohesion is a measure of how strongly related and focused responsibilities of an element are.

Problem How to keep classes focused, understandable and manageable?


Solution Assign a responsibility so that cohesion remains high.

An element has high cohesion if it,


• Does not do tremendous work
• Has high responsibilities

Difficulties of low cohesion are


• Hard to comprehend
• Hard to reuse
• Hard to maintain

Example
Create a payment instance and associate it with sale
Design 1
 Register records a payment in real world
 Then it sends addpayment message to sale, passing newpayment as a parameter.

Design 2
In the second design, payment creation is the responsibility for sale.
• It is highly desirable because it supports
◦ High cohesion and
◦ Low coupling

Scenarios of varying degrees of functional cohesion


(1) Very low cohesion
A class is solely responsible for many things in different functional areas.
(2) Low cohesion
A class has sole responsibility for a complex task in one functional area.
(3) High cohesion
A class has moderate responsibilities in one functional area and collaborates with others.
(4) Moderate cohesion
A class has light weight. It is responsible for different areas logically related to the class concept .

Benefits of high cohesion are


1) Clarity
2) Ease of comprehension
3) Reuse of fine-grained, highly related functionality.
5.Controller

A controller is defined as the first object beyond the user interface (UI) layer that is responsible for the
receiving or handling a system operation message.

Problem
what first object beyond the UI layer that receives and coordinates a system operation?

Solution
Assign the responsibility of controller to an object representing one of the following choices
 Represents the overall system, device, or subsystem.
 Represents a use case scenario within which the system event occurs.

Example
NextGen application contains several system operations.

During the design the responsibility of system operations is done by the controller.
The controller are
1) Register POS system – Represents overall system.
2) Process Sale handler – Represents receiver/handler of system events.

Explain GOF Design Pattern in Detail

In 1994, four authors Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides published a book
titled Design Patterns - Elements of Reusable Object-Oriented Software. These authors are collectively
known as Gang of Four (GOF).

1. Factory Pattern
 Factory pattern is one of most used design pattern in Java.
 In Factory pattern, we create object without exposing the creation logic to the client and refer to
newly created object using a common interface.
Problem
Who is responsible for creating objects that are required for complex creation logic?
Solution
Create a pure fabrication object called Factory that handles the creation.
Implementation
Create a Shape interface and concrete classes implementing the Shapeinterface. FactoryPatternDemo,
class will use ShapeFactory to get a Shape object. It will pass information (CIRCLE / RECTANGLE /
SQUARE) to ShapeFactory to get the type of object it needs.
Step 1 Create an interface.
Step 2 Create concrete classes implementing the same interface.
Step 3 Create a Factory to generate object of concrete class based on given information.
ShapeFactory.java
Step 4 Use the Factory to get object of concrete class by passing information such as type.
Step 5 Verify the output.
2.Singleton pattern
 Singleton pattern is one of the simplest design patterns in Java
 Singleton Pattern says that just "define a class that has only one instance and provides a global
point of access to it"
There are two forms of singleton design pattern
 Early Instantiation: creation of instance at load time.
 Lazy Instantiation: creation of instance when required.
Problem:
Singleton pattern is created in a situation in which only one instance of a class must be created and this
instance can be used as a global point of access.
Solution:
Define a static method of the class that returns singleton.
Implementation:
 Create a SingleObject class.
 SingleObject class has its constructor as private.
 SingleObject class provides a static method to get its static instance to outside world.
 SingletonPatternDemo, class will use SingleObject class to get a SingleObject object.

Step 1: Create a Singleton Class.

public class SingleObject {


private static SingleObject instance = new SingleObject();
private SingleObject(){ }
public static SingleObject getInstance(){
return instance;
}
public void showMessage(){
System.out.println("Hello World!");
}
}
Step 2 :Get the only object from the singleton class.
public class SingletonPatternDemo {
public static void main(String[] args) {

SingleObject object = SingleObject.getInstance();


object.showMessage();
}
}

Step 3: Verify the output.

Hello World!

3.Adapter Pattern
Adapter pattern works as a bridge between two incompatible interfaces. This type of design pattern comes
under structural pattern as this pattern combines the capability of two independent interfaces.
Problem:
How to resolve incompatible interfaces. How to provide a stable interface to the intermediate having
different interfaces?
Solution:
Convert the original interface of component into another interface through intermediate adapter object.
Implementation:

We have a MediaPlayer interface and a concrete class AudioPlayer implementing the MediaPlayer
interface. AudioPlayer can play mp3 format audio files by default. We are having another interface
AdvancedMediaPlayer and concrete classes implementing the AdvancedMediaPlayer interface. These
classes can play vlc and mp4 format files.
We want to make AudioPlayer to play other formats . To attain this, we have created an adapter class
MediaAdapter which implements the MediaPlayer interface and usesAdvancedMediaPlayer objects to
play the required format. AdapterPatternDemo, our demo class will use AudioPlayer class to play various
formats.

4.Observer Pattern

The Observer pattern is a design pattern that defines a link between objects so that when one objects state
changes, all dependent objects are updated automatically.
Problem:
What could be done when some object generates an event and in response to that event different kinds of
subscriber objects changes the state.
Solution:
Define the subscriber interface. The publisher dynamically registers the corresponding subscribers and
notifies them when some event occurs.
Implementation:
Consider that a school sends the notice to the students via some SMS or by email. The notification system
works as soon as some event occurs. For example – if the notice like “ Due to heavy rainfall the school
will remain closed today” can be sent to the students either as a SMS or as an email when heavy rainfall
occurs. Here the school Notification system object will act as a publisher and student object will be
subscriber.
Explain in detail about the mapping of design to code implementation in an object oriented
language.
(or)
Explain about the implementation model.
(or)
Explain in detail the design artifacts to implementation code in an object oriented language.

Mapping design to code:

 The interaction diagram and class diagrams can be used as input to the code generation process.
 Various object oriented languages such as Java++, C#, Small talk. Python and so on can be used
as the language of implementation.
 Implementation in an object oriented language requires writing source code for
 Class and interface definitions.
 Method Definitions.

Defining a Class with Methods and Simple Attributes

The class diagram consists of classes, interfaces, super classes, methods and attributes.
These elements are sufficient to create basic class definition in any object oriented language like java.
Mapping the methods and attributes from the class diagram is straight forward.

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.
In this example, SalesLineItem that refers to a ProductSpecification instance.
Reference Attributes and Role Names
 Each end of an association is called a role.
 Role name is a name that identifies the role
 If a role name is present in a class diagram, use it as the name of the reference attribute during
code generation.

Creating Methods from Interaction Diagrams

The sequence of messages in an interaction diagram translates to series of statements in the method
definitions.
Here, enterItem, message is sent to register instance.

public void enterItem (int, ietmID, int qty)

Message 1:

A getProductDescription is sent to the Product catalog to retrieve Product Description.

ProductDescription desc = catalog.getProduct Description (itemID);

Message 2:

The makeLineItem message is sent to the sale.

CurrentSale.makeLineItem (desc, qty);

Collection Classes in Code

 The one to many relationship can be implemented as the collection object.


 The collection object can be Map, vector, List or Arrays.
 The java libraries consist of the collection classes such as Array List and Hash Map which
implements List and Map interfaces respectively.
Explain Bridge and Strategy Pattern in detail.

Bridge Pattern

 Bridge is used when we need to decouple an abstraction from its implementation so that the
two can vary independently.
 This type of design pattern comes under structural pattern as this pattern decouples
implementation class and abstract class by providing a bridge structure between them.

Implementation

Step 1 Create bridge implementer interface.

Step 2 Create concrete bridge implementer classes implementing the DrawAPI interface.

Step 3 Create an abstract class Shape using the DrawAPI interface.

Step 4 Create concrete class implementing the Shape interface.

Step 5 Use the Shape and DrawAPI classes to draw different colored circles.

Step 6 Verify the output.


Strategy Pattern:

In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design
pattern comes under behavior pattern.

Implementation:

Create a Strategy interface defining an action and concrete strategy classes implementing the Strategy
interface. Context is a class which uses a Strategy. StrategyPatternDemo will use Context and strategy
objects to demonstrate change in Context behaviour based on strategy it deploys or uses.

Step 1 Create an interface.

Step 2 Create concrete classes implementing the same interface.

Step 3 Create Context Class.

Step 4 Use the Context to see change in behaviour when it changes its Strategy.

Step 5 Verify the output.


Important 2 Mark Questions with Answers

1. What is GRASP?

General Responsibility Assignment Software Patterns (or Principles) consists of guidelines for assigning
responsibility to classes and objects in object- oriented design.

2. What is responsibility?

The UML defines are responsibility as ―”a contract or obligation of a classifier”. Responsibilities are
related to the obligations or behavior of an object in terms of its role.

 Doing responsibility
 Knowing responsibility

3. What is design pattern?

A design pattern is a general reusable solution to a commonly occurring problem in software design.

 Creational patterns
 Structural patterns
 Behavioral patterns

4. Define patterns.

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.

You might also like