UNIT4
UNIT4
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
GRASP
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?
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.
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
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.
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.
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.
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.
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.
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.
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.
Message 1:
Message 2:
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 2 Create concrete bridge implementer classes implementing the DrawAPI interface.
Step 5 Use the Shape and DrawAPI classes to draw different colored circles.
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 4 Use the Context to see change in behaviour when it changes its Strategy.
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
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.