Ooad - Unit 4
Ooad - Unit 4
Ooad - Unit 4
GRASP
The GRASP is a tool that helps to master the basics of OOD and understanding
responsibilities.
GRASP is a learning aid that helps to understand the essential object design and apply the
design in a methodical, rotational and explainable way.
RDD
RDD is a general metaphor for thinking about object oriented design.
The responsibilities include
• Doing responsibility creating action, initializing, controlling and
coordinating activities
• Knowing responsibilities includes knowing about private and related data.
CREATOR
Problem
One of the most common activities in object oriented system is creation of objects.
General principle is applied for the assignment of creation responsibilities.
Design supports
• Low coupling
• Increased clarity
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
• Encapsulation
• Reusability
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
• B is an expert while creating A (B passes the initializing data for A that is passed to A
when created).
If more than one option is true.
Class B aggregates or contains class A.
Example
NEXTGen POS Application
We have to find who is the creator of SalesLineItem instance.
Consider the partial domain model of SaleLineItem.
Here ‗Sale‘ takes the responsibility of creating ‗SalesLineItem‘ instance. Since sale
contains many ‗SalesLineItem‘ objects.
While assigning responsibilities ‗makeLineitem‘ must also be defined in ‗Sale‘.
The creator pattern finds a creator that needs to be connected to the created event.
The common task of creator is to assign responsibilities related to the creation of objects.
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
Contradictions:
Based on some external value, creation requires complexity like
• Recycled instances for performances.
• Creating an instance from one of a family of similar classes based an external
property etc.
• Abstract factory or
• Concrete façade
Then use the class of creator.
Benefits
• Lower maintenance due to low coupling
• Higher opportunities for reuse
After adding the getTotal( ), the partial interaction and class diagrams given as
SalesLineitem.quantity’
ProductDescription.price
After knowing and answering subtotal, a SalesLineItem has to know product price.
ProductDescription is an information expert for answering price.
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
Finally, three design classes, assigned with three responsibilities to find sales total.
LOW COUPLING
Coupling is the measure of low 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
systems it is having low coupling.
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
Example
Design 2:
Suggested by low coupling
1) Here sale does the creation of payment.
2) It does not increase coupling and hence preferred.
HIGH COHESION
Cohesion is a measure of how strongly related and focused responsibilities of an element
are. 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
• Delicate
Example
Create a payment instance and associate it with sale
Design 1
• Register records a payment in real world
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.
Example:
1) A cashier is POS terminal pressing ―EndSale‖ button indicating ―sale has ended‖
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
2) Writer using word processor presses ―spell check‖ button to perform checking of
spelling
Solution
Assign responsibility to one of the following
• Represents overall ―system‖, ―a root object‖
◦ These are variations of façade controller.
• Represents a usecase scenario called
◦ <usecaseName> handler
◦ <usecaseName> coordinator or
◦ <usecaseName> session
Here we use some controller class for all system events in same usecase scenario.
A session is an instance of a conversation with an actor.
Example:
NextGen application contains several system operations.
A controller should assign other objects the work that needs to be done.
It coordinates or controls the activity. Same controller class can be used for all
system events to maintain information about the state of usecase.
A common defect in the design of controllers is it suffers from bad cohesion.
Controllers
The facade controller represents the overall system, device or a sub system.
Choose some class name that suggests a cover or faced over other layers of the application
that provides main service calls from UI layer down to the other layers.
Facade controllers are used
1) Where there are not ―too many‖ system events
2) When the UI (User Interface) cannot redirect system event messages.
In used case controller there is a different controller for each use case. Facade controllers
lead to low cohesion or high coupling design.
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
So usecase controllers are good when there are many system events across different
processes.
• Boundary objects
• Entity objects
• Control objects
Boundary objects : Abstractions of the interfaces
Entity objects : Application independent domain software objects
Control objects : Use case handless
An important corollary of the controller pattern is UI objects.
System operations should be handled in application logic or domain layer of objects rather
than UI layer of a system.
Web UIs and saver side application of controller
An approach used is
ASP.NET and webforms:
• Developers insert application logic handling in the ―code behind‖ file, mixing
application logic into the UI layer.
• Server side web UI frameworks embody the concept of web MVC (Model – view -
controller) pattern.
• Choosing server technical frameworks strongly influence handling of serverside
system operation.
• To lower the coupling of UI, the clientside UI forwards the request to the local client side
controller.
Benefits
1) Increased potential for reuse and pluggable interfaces.
2) Opportunity to reason about the state of the use case.
Implementation with Java Swing : Rich Client UI:
We deal with basic swing. The code has
1) ProcessJFrame window referring to domain controller object – Register
2) Define handler for button click.
3) Show key message – sending enterItem message to the controller.
Code
package.com.nextgen.ui.swing;
//import
public class ProcessSaleJFrame extends JFrame
{
//window refers to ‗controller‘ domain object
(1) private Register register
public ProcessSaleJFrame (Register-register)
{
register = -register;
}
private JButton BTN_ENTER_ITEM /* this button is clicked to perform sys operation
―enetrItem‖*/
———
———
——
(2) BTN_ENTER_ITEM.addActionListener (new ActionListener ( )
{
public void actionPerformed (ActionEvent e)
{
// utility class
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
———
———
(3) register.enterItem(id, qty);
}
}); // end of ActionListerner
return BTN_ENTER_ITEM;
}// end of method
———
}
Implementation with java statements: Client Browser and WebUI
1) Obtain a reference to the Register domain object.
2) Send ―enterItem‖ message to domain controller object.
Code:
package.com.nextgen.ui.web;
//import
public class EnterItemAction extends Action
{
public ActionForward execute (ActionMapping mapping,
ActionForm form, HttpServletRequest request, HttpServlet Response
response) throws exception
———
———
(1) Register register = repository.getRegister ( );
———
———
(2) register.enterItem (id, qty);
}// end of method
} // end of class
A controller class has low cohesion i.e. unfocused and handling many responsibilities. It
is called bloated controller.
• When facade controller is chosen, a single controller class receives all system events.
• Violating information expert and high cohesion controller itself performs many of the tasks.
• Controller has many attributes.
These are signs of bloated controller.
Cures for bloated controllers
1) Add more controllers
Example: Airline Reservation may have
Related patterns
• Command Each message is a command object
• Facade Facade controller is kind of facade
• Layers Domain logic in domain layer than presentation layer
• Pure fabrication A use case controller
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
DESIGN PATTERNS
Designing for Visibility
The ability of one object to have reference of another is called visibility.
Example:
The getProductDescription message sent from a Register to a product catalog means that
ProductCatalog instance is visible to register.
Parameter visibility
Here B passes as parameter to A when parameter visibility exists.
It persists only within the scope of the method.
So it is relatively temporary visibility.
Example:
When makeLineItem is sent to a sale instance, a ProductDescription instance is passed as
a parameter.
Local visibility
It exists from A to B when B is declared as a local object within a method of A.
It persists only within the scope of the method. So it is relatively temporarily
visible. The local visibility is achieved by
• Creating a new local instance and assigning to a local variable
• Assign the returning object from a method invocation to a local variable.
Global visibility
Here global visibility is achieved from A to B if B is global to A. It persists as long as A and B
exist. So it is permanent visibility. To achieve global visibility,
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
FACTORY METHOD
It is called as
• Simple factory or
• Concrete factory
It is the simplification of GOF abstract factory.
Next adapter raises the problem,
• Who create adapters?
• How to create adapters?
When domain objects create the adapter, their responsibilities are beyond pure application
logic and related to connectivity with other software components.
So, when a domain object creates adapters
(i) It does not support goal of separation of concerns.
(ii) It lowers cohesion.
So we go in for ‗factory‘ pattern, where pure fabrication ―factory‖ object is defined to
create objects.
Advantages of factory
(i) Separate the responsibility of complex creation into cohesive helper objects.
(ii) Potential complex creation is hidden.
(iii) Performance-enhancing memory management strategies such as object catching
or recycling are allowed.
Strategies such as object catching or recycling is allowed.
Name : Factory
Problem : For complex creation logic, for better cohesion who is responsible for creating
objects.
Solution : A pure fabrication object called ‗factory‘ is created that handles creation.
In ‗Service Factory‘, the logic to decide the class creation is resolved by reading
in the class name from external source.
This is called ―datadriven design‖
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
ADAPTER
Name : Adapter
Problem : If similar components have different interfaces then how to
resolve incompatible interfaces.
Solution : Using an intermediate adapter object, convert original interface of
a component to another interface.
The NextGen POS system supports many third party services like,
• Tax calculators
• Credit authorization services
• Inventory systems
• Accounting systems etc
Add a level of indirection with objects to adapt to the solution.
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
Type names are given by pattern name, ―Adapter‖, to communicate the user of the design
pattern being used.
A resource adapter that hides external system is considered as façade object.
The motivation to call resource adapter exist when wrapping objects provide adaptation.
Adapter and GRASP
SINGLETON (GOF)
With the services factory, we have a problem who creates the factory.
One instance of factory is needed with the process.
Since at different places the adapter are called, the quick reflection suggest that the
methods of this factory may need to be called form various places in code.
This problem can be solved by passing ‗Service factory‘ as a parameter, initialize the
objects that need visibility.
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
Name : Singleton
Problem : Exactly one instance of class allowed called ―Singleton‖. Objects are global and
have single point of access.
Solution : Static method of class is defined, that returns singleton.
OBSERVER PATTERNS
To extend the solution found for changing data, add the ability for a GUI window to
refresh its sale.
The model-view separation principle discourages such solutions. It states that ―Model‖
objects should not know about view or presentation objects such as window.
It promotes Low coupling.
Due to low coupling the replacement of the view or presentation layer by a new one or of
particular windows by new windows.
The variations are supported by model view separation.
Applying UML
The OnPropertyEvent message is polymorphic in the above interaction diagram.
In the diagram below, SaleFrame1 implements PropertyListener interface thus
implements onPropertyEvent.
SaleFrame1 on receiving the message sends to JTextFieldGUI widget object to refresh
with new Saletotal.
Events:
In java and C#.NET implementation of observer, ‗event‘ is shown as regular message such as
onPropertyEvent.
In these cases, the event is defined as class and filled with event data.
Event is then passes as a parameter in event message.
Example:
class PropertyEvent extends Event
{
private object sourceOfEvent;
private string propertyName;
private object oldvalue;
private object newvalue;
//…
}
class sale
{
private void publishPropertyEvent (string name, object old, object new)
{
PropertyEvent evt = new PropertyEvent (this, ―sale-total‖, old, new); for each
AlarmListener al in alarm Listeners al.onPropertyEvent (evt);
}
//…
}
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
Java
In 1996, the observable-observer design was replaced by Java Delegation Event Model
(DEM) version of publish-subscribe.
Observer thus provides a way to couple objects for communication.
Publishers/subscribers are to register with publisher.
We conclude that, Observer is based on polymorphism that provides protected variations
for protecting publishers from knowing specific class of object and number of objects that
communicates with publisher to generate event.
The java constructor salesLineItem (…) is derived from create (desc, qty) message sent to
SalesLineItem in the enterItem interaction diagram.
Creating Methods from Interaction Diagrams
The sequence of messages in an interaction diagram translates to series of statements in
the method definitions.
Message 2:
The makeLineItem message is sent to the sale.
CurrentSale.makeLineItem (desc, qty);
Each sequence message is mapped to the statement in the java method.
The complete enterItem method and its relationship to interaction diagram is given below
Order of Implementation
Implementation of least-coupled classes is done followed by most coupled classes.
Example:
First classes payment/product Description is implemented.
Next Product catalog / SaleLineItem are implemented.
Possible order of class Implementation and testing
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
class Productcatalog:
{
private Map<ItemID, ProductDescription>
description = newHashMap ( )
<ItemID, ProductDescripion>;
public ProductCataglog( )
{
// Sample Data
ItemID id1 = new ItemID (10);
ItemID id2 = new ItemID (20);
money price = new Money (3);
product Description d;
d = new Product Description (id1, price, ‗Product
1‘); description put (id1, d);
d = new Product Description (id2, price, ‗Product
2‘); description put (id2, d);
}
public Product Description getProductDescription (ItemID id)
return description get (id);
}
class Register:
public class Register
{
private Product Catalog Catalog;
private Sale currentSale;
public Register (ProductCatalog Catalog)
{
this.catalog = catalog;
}
public void endSale ( )
{
currentSale.become Complete ( );
}
public void enterItem (ItemID id, int quantity)
{
productDescription desc = catalog.getProductDescription
(id); currentSale.makeLineItem (desc, quantity);
}
public void makeNewSale ( )
{
currentSale = newSale ( );
}
public void makePayment (Money cashTendered)
{
currentSale.makePayment( cashTendered);
}
}
class Productdescription
public class ProductDescription
{
private ItemID id;
private Money price;
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
return faceValue
}
}
Class Board
public class Board
{
private static final int SIZE = 40;
private List squares = new ArrayList (SIZE);
public Board ( )
{
build squares ( );
link Squares ( );
}
public Square getSquare (Square start, int distance)
{
int endIndex = (start.getIndex( ) + distance)
%size; return (Square) Square.get (endIndex);
}
public Square getstartSquare ( )
{
return (Square) Squares.get (0);
}
private void bulidSquare ( )
{
for (int i=1 i<=SIZE; i++)
{
build (i);
}
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE
}
private void build (int i)
{
Square S = new Square (―Square‖ +I, i-1);
Square.add(S);
}
private void linkSquare ( )
{
for (int i=0;i<(SIZE-1); i++)
{
link (i);
}
Square first = (square) Square.get(0);
Square last = (square) Square.get(SIZE-);
last.setNextSquare (first);
}
private void link (int i)
{
Square current = (Square) Squares.get(i);
Square next = (Square) Squares.get(i+1);
current.setNextSquare (Next);
}
}
Class player
public class player
{
private string name;
private Piece piece;
private Board board;
private Die [ ] dice;
public player (string name, Die [ ] dice, Board board)
{
this.name = name;
this.dice = dice;
this.board = board;
piece = new Piece (board.getstartsquare ( ));
}
public void take turn ( )
{
int roll Total = 0;
for (int i =0; i<dice.length; i++)
{
dice [i].roll ( );
rollTotal += dice[i].getFaceVlaue ( );
}
Square newLoc = board.getSquare (Piece.getLoaction ( ), rollTotal);
piece.setLocation(newLoc);
}
public square getLocation ( )
{
return piece.getLocation ( );
}
VEL TECH HIGH TECH Dr.RANGARAJAN Dr.SAKUNTHALA ENGINEERING COLLEGE