SlideShare a Scribd company logo
1 of 23
Download to read offline
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 1
CS8592 – Object Oriented Analysis and Design
UNIT IV – Design Patterns
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
4.1 GRASP: DESIGNING OBJECTS WITH RESPONSIBILITIES
General Responsibility Assignment Software Patterns (or Principles), abbreviated GRASP, consist
of guidelines for assigning responsibility to classes and objects in object-oriented design.
Responsibility in software is a very important concept and not only concerns classes but also modules
and entire systems.
 What is the responsibility of this class/module/component/system?
 Is it responsible for this or is it responsible for that?
 Is Single Responsibility Principle violated in this particular context?
Reference Code:
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 2
Doing and Knowing
Doing responsibility of an object is seen as:
a) Doing something itself – create an object, process data, do some computation/calculation
b) Initiate and coordinate actions with other objects
Knowing responsibility of an object can be defined as:
a) Private and public object data
b) Related objects references
c) Things it can derive
The list of 9 GRASP patterns (sometimes called principles but please, do not focus on naming here):
Every programmer and designer should be familiar with these patterns and what is more important –
know how to apply them in everyday work.
1. Information Expert
2. Creator
3. Controller
4. Low Coupling
5. High Cohesion
6. Indirection
7. Polymorphism
8. Pure Fabrication
9. Protected Variations
4.1.1 Information Expert
Problem: What is a basic principle by which to assign responsibilities to objects? Solution: Assign a
responsibility to the class that has the information needed to fulfill it.
In following example Customer class has references to all customer Orders so it is natural candidate to
take responsibility of calculating total value of orders:
4.1.2 Creator
The goal is to define the creator object.
Problem: Who creates object A?
Solution: Assign class B the responsibility to create object A if one of these is true more is better)
– B contains or compositely aggregates A
– B records A
– B closely uses A
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 3
– B has the initializing data for A
4.1.3 Controller
Problem: What first object beyond the UI layer receives and coordinates ―controls‖ a system operation?
Solution: Assign the responsibility to an object representing one of these choices:
 Represents the overall ―system‖, ―root object‖, device that the software is running within, or a
major subsystem (these are all variations of a facade controller)
 Represents a use case scenario within which the system operation occurs (a use case or session
controller)
 This principle implementation depends on high level design of our system but general we need
always define object which orchestrate our business transaction processing.
4.1.4 Low Coupling
Problem: How to reduce the impact of change? How to support low dependency and increased reuse?
Solution: Assign responsibilities so that (unnecessary) coupling remains low. Use this principle to
evaluate alternatives.
Coupling is a measure how one element is related to another. The higher the coupling, the greater the
dependence of one element to another.
Low coupling means our objects are more independent and isolated.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 4
4.1.5 High Cohesion
Problem: How to keep objects focused, understandable, manageable and as a side effect support Low
Coupling?
Solution: Assign a responsibility so that cohesion remains high. Use this to evaluate alternatives.
Cohesion is a measure how strongly all responsibilities of the element are related. In other words, what
is the degree to which the parts inside an element belong together.
Classes with low cohesion have unrelated data and/or unrelated behaviors. For example, the Customer
class has high cohesion because now it does only one thing – manage the Orders.
4.1.6 Indirection
Problem: Where to assign a responsibility to avoid direct coupling between two or more things?
Solution: Assign the responsibility to an intermediate object to mediate between other components or
services so that they are not directly coupled.
The indirection pattern supports low coupling and reuse potential between two elements by assigning the
responsibility of mediation between them to an intermediate object. This ensures that coupling between
them remains low.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 5
4.1.7 Polymorphism
Problem: How handle alternatives based on type?
Solution: When related alternatives or behaviors vary by type (class), assign responsibility for the
behavior (using polymorphism operations) to the types for which the behavior varies.
Polymorphism is fundamental principle of Object-Oriented Design. In this context, principle is strongly
connected with (among others) Strategy Pattern.
Polymorphism implies using operations in different ways, depending upon the instance they are
operating upon. Polymorphism allows objects with different internal structures to have a common
external interface. Polymorphism is particularly effective while implementing inheritance.
By sending message to the Shape object, a call will be made to the corresponding sub class object –
Circle or Triangle.
4.1.8 Pure Fabrication
Problem: What object should have the responsibility, when you do not want to violate High Cohesion
and Low Coupling but solutions offered by other principles are not appropriate? Solution: Assign a
highly cohesive set of responsibilities to an artificial or convenience class that does not represent a
problem domain concept.
For example, in e-commerce systems we often have needed to convert one currency to another.
Sometimes it is hard to say where this behavior should be placed so the best option is to create new class
and interface.
4.1.9 Protected Variations
Problem: How to design objects, subsystems and systems so that the variations or instability in these
elements does not have an undesirable impact on other elements?
Solution: Identify points of predicted variation or instability; assign responsibilities to create a stable
interface around them.
This is the most important principle which is indirectly related to the rest GRASP principles. Currently,
one of the most important software metrics is the ease of change. As architects and programmers we
must be ready for ever-changing requirements.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 6
4.2 DESIGN PATTERNS
 Pattern is a named description of a problem and solution that can be applied to new context.
 Software Pattern provides a generable reusable solution to a common reusable design problem
and it guides the assignment of responsibilities to objects.
 It shows the relationships and interactions between classes (or) objects.
 Object Design is the process of adding details to the requirement analysis and making
implementation decision.
 Activities of object design are
– Start Coding immediately
– Start some UML modeling for object design
– Start with another modeling technique such as CRC cards.
4.2.1 Software Patterns
 Software Patterns consists of four parts in it
 Pattern Name
 Problem
 Solution
 Consequences
 Example
– Pattern Name-Information Expert
– Problem-What is the basic principle to assign responsibilities to objects?
– Solution- Assign a responsibility to the class that has the information needed to fulfill it.
– Consequences-What other objects will be affected by assigning responsibilities to an object?
4.2.2 Refactoring
 Refactoring is a systematic process of improving code without creating new functionality that
can transform a mess into clean code and simple design.
 Clean code is code that is easy to read, understand and maintain. Clean code makes software
development predictable and increases the quality of a resulting product.
 Performing refactoring step-by-step and running tests after each change are key elements of
refactoring that make it predictable and safe.
4.3 THE “GANG OF FOUR” (GOF) DESIGN PATTERNS
 Design Patterns: Elements of Reusable Object-Oriented Software (1994) is a software
engineering book describing software design patterns. The book was written by four authors
chapters describing 23 classic software design patterns.
 Four authors: Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides
 Patterns suggest opportunities for reuse in analysis, design and programming
4.3.1 Three Types ofPatterns
 Creational Patterns (5 Types): Dealwith initializing and configuring classes and objects.
 Structural Patterns (7 Types): Dealwith decoupling interface and implementation of classes
and objects. Composition of classes or objects.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 7
 Behavioral patterns (11 Types): Dealwith dynamic interactions classes and objects. How they
distribute responsibility.
4.3.2 Creational Patterns
 Abstract Factory: Factory for building related objects
 Builder: Factory for building complex objects incrementally
 Factory Method: Method in a derived class creates associates
 Prototype: Factory for cloning new instances from a prototype
 Singleton: Factory for a singular (sole) instance
4.3.3 Structural Patterns
 Adapter: Translator adapts a server interface for a client
 Bridge: Abstraction for binding one of many implementations
 Composite: Structure for building recursive aggregations
 Decorator: Decorator extends an object transparently
 Facade: Simplifies the interface for a subsystem
 Flyweight: Many fine-grained objects shared efficiently.
 Proxy: One object approximates another
4.3.4 Behavioral Patterns
 Observer: Dependents update automatically when subject changes
 State: Object whose behavior depends on its state
 Strategy: Abstraction for selecting one of many algorithms
 Template Method: Algorithm with some steps supplied by a derived class
 Visitor: Operations applied to elements of a heterogeneous object structure
4.4 FACTORYMETHOD PATTERN
 A creational design pattern that provides an interface for creating objects in a superclass, but
allows subclasses to alter the type of objects that will be created.
 This is also called as Simple Factory or Concrete Factory.
 Problem: Who should be responsible for creating objects when there are special considerations
such as complex creation logic, a desire to separate creation responsibilities for better cohesion,
etc.?
 Solution: Create a Pure Fabrication object called a Factory that handles the creation.
 A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class
for creating an object but let the subclassesdecide which class to instantiate. In other words,
subclasses are responsible to create the instance of the class.
 For example,both Truck and Ship classes should implement the Transport interface, which
declares a method called deliver.
 Each class implements this method differently: trucks deliver cargo by land, ships deliver cargo
by sea.
 The factory method in the RoadLogistics class returns truck objects, whereas the factory method
in the SeaLogistics class returns ships.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 8
 Merits and Demerits of Factory Pattern Method
o Merits
– The code becomes flexible and loosely coupled
– The client code deals only with factory interface. Hence if new object is required then it
can be added without disturbing the client code.
– Can return same instance multiple times
– Brings consistency in the code
o Demerits
– The class has to be refactored
– Sub class needs to provide reimplementation for all factory methods
– Code becomes complex
4.5 ABSTRACT FACTORY PATTERN
 A creational design pattern that lets you produce families of related objects without specifying
their concrete classes.
 A factory is a class that returns products of a particular kind.
 Declare the Abstract Factory an interface with a list of creation methods for all products that are
part of the product family
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 9
 For each variant of a product family, we create a separate factory class based on the
AbstractFactory interface.
 Example: The ModernFurnitureFactory can only create ModernChair, ModernSofa and
ModernCoffeeTable objects.
 The client code has to work with both factories and products via their respective abstract
interfaces.
 This lets you change the type of a factory that you pass to the client code, as well as the product
variant that the client code receives, without breaking the actual client code.
 Example-Next Gen POS System for Abstract Factory Pattern
4.6 SINGLETON PATTERN
 A creational design pattern that lets you ensure that a class has only one instance, while
providing a global access point to this instance.
 Problem: Exactly one instance of a class is allowed. Objects need a global and single point of
access.
 Solution: Define a static method of the class that returns the singleton: getInstance()
 Singleton supports global visibility or a single access point to a single instance.
4.6.1 Implementations ofthe Singleton
 Make the default constructor private, to prevent other objects from using the new operator
with the Singleton class.
 Create a static creation method that acts as a constructor. Under the hood, this method calls
the private constructor to create an object and saves it in a static field. All following calls to
this method return the cached object.
 In singleton pattern getInstance method is frequently used.
ServicesFactory
accountingAdapter : IAccountingAdapter
inventoryAdapter : IInventoryAdapter
taxCalculatorAdapter : ITaxCalculatorAdapter
getAccountingAdapter() : IAccountingAdapter
getInventoryAdapter() : IInventoryAdapter
getTaxCalculatorAdapter() : ITaxCalculatorAdapter
...
note that the factory methods
return objects typed to an
interface rather than a class, so
that the factory can return any
implementation of the interface
if ( taxCalculatorAdapter == null )
{
// a reflective or data-driven approach to finding the right class: read it from an
// external property
String className = System.getProperty( "taxcalculator.class.name" );
taxCalculatorAdapter = (ITaxCalculatorAdapter) Class.forName( className ).newInstance();
}
return taxCalculatorAdapter;
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 10
 Example: The database connection class acts as a Singleton. This class doesn’t have a public
constructor, so the only way to get its object is to call the getInstance method. This method
caches the first created object and returns it in all subsequent calls.
class Singleton
{ public:
static Singleton* getInstance();
protected: //Why are the following protected?
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private: static Singleton* instance;
};
Singleton *p2 = p1->getInstance();
4.6.2 Merits ofSingleton Pattern
 It provides controlled access to sole instance.
 It permits the refinement of operations and representations.
 It is useful when only one instance of class must be created and accessible to clients from well-
known access point.
4.7 ADAPTER PATTERN
 A structural design pattern that allows objects with incompatible interfaces to collaborate.
 Problem: How to resolve incompatible interfaces or how to 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.
 Note: The Adapter pattern is an application of Polymorphism. Adapter pattern follows GRASP
principles: Polymorphism, Protected Variation, Indirection.
 Adapters cannot only convert data into various formats but can also help objects with different
interfaces collaborate. Here’s how it works:
o The adapter gets an interface, compatible with one of the existing objects.
o Using this interface, the existing object can safely call the adapter’s methods.
o Upon receiving a call, the adapter passes the request to the second object, but in a format
and order that the second object expects.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 11
 Example: When you travel from the US to Europe for the first time, you may get a surprise
when trying to charge your laptop. The power plug and sockets standards are different in
different countries. That’s why your US plug won’t fit a German socket. The problem can be
solved by using a power plug adapter that has the American-style socket and the European-style
plug.
 In the adapter pattern example given for NextGen POS System
iAccountingAdapter(incompatible) interface has to send values to intermediate adapter
 iCreditcardAuthorizationService(compatible) adapter.
 See figure for conceptual connection among GRASP principles and Adapter pattern
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 12
4.7.1 Relating Adapter Pattern to GRASP Principles
4.7.2 Merits of Adapter Pattern
 Merits
o Two compatible objects or classes can be interfaced using adapter patterns
o Reduces coupling between the objects
o If we have several modules implementing same functionality then write adapters for them,
the adapters are implementing the same interface
 Demerits
o It makes the code complex and difficult to debug.
4.8 BRIDGE PATTERN
 A structural design pattern that lets you split a large class or a set of closely related classes into
two separate hierarchies—abstraction and implementation—which can be developed
independently of each other.
 Problem: Occurs when extending classes of similar type
 Solution: The Bridge pattern attempts to solve this problem by switching from inheritance to the
object composition. What this means is that you extract one of the dimensions into a separate
class hierarchy, so that the original classes will reference an object of the new hierarchy, instead
of having all of its state and behaviors within one class.
 Example: We can extract the color-related code into its own class with two
subclasses: Red and Blue.
 The Shape class then gets a reference field pointing to one of the color objects.
 Now the shape can delegate any color-related work to the linked color object.
 That reference will act as a bridge between the Shape and Color classes.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 13
 From now on, adding new colors won’t require changing the shape hierarchy, and vice versa.
4.8.1 Bridge Pattern Representation
 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.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 14
4.8.2 Merits and Demerits ofBridge Pattern
 Merits
o Separates the implementation from interface
o It can be used when the class vary quite often
o It is useful in graphic toolkits that need to run on multiple platforms
o Implementation details can be effectively hidden from the client so that client focus an just
the behavior desired
 Demerits
o Due to separation of interface and implementation it increases the complexity of client
program
o Performance of overall code is decreased
4.8.3 Difference between Bridge and Adapter Pattern
Bridge Pattern Adapter Pattern
Bridge pattern is used to decouple an abstraction
class from its implementation.
Converts the interface between the classes with
less inheritance.
Used when class vary quite often.
Used to make existing classes to work with other
without modifying their source code.
Used in graphics toolkit.
Used when two incompatible interfaces need to
work together.
Implementation details can be hidden from the
client.
Adapter acts as translator between two types.
4.9 OBSERVER PATTERN
 A behavioral design pattern that lets you define a subscription mechanism to notify multiple
objects about any events that happen to the object they’re observing.
 Problem: Different kinds of subscriber objects are interested in the state changes or events of a
publisher object, and want to react in their own way when the publisher generates the event.
 Solution: Define a ―subscriber‖ or ―listener‖ interface. Subscribers implement this interface.
The publisher can dynamically register subscribers who are interested in an event, and notify
them when an event occurs.
 Example:
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 15
 The object that has some interesting state is often called subject, but since it’s also going to
notify other objects about the changes to its state, we’ll call it publisher.
 All other objects that want to track changes to the publisher’s state are called subscribers.
 The Observer pattern suggests that you add a subscription mechanism to the publisher class so
individual objects can subscribe to or unsubscribe from a stream of events coming from that
publisher.
 Publisher generates events and subscriber can subscribe or unsubscribe to that particular event.
Publisher can have n number of subscribers.
 Publisher notifies by calling the specific notification method on their objects to it’s subscribers
4.9.1 Observer Pattern Representation
 The Publisher issues events of interest to other objects. These events occur when the publisher
changes its state or executes some behaviors.
 When a new event happens, the publisher goes over the subscription list and calls the notification
method declared in the subscriber interface on each subscriber object.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 16
 The Subscriber interface declares the notification interface. In most cases, it consists of a
single update method.
 Concrete Subscribers perform some actions in response to notifications issued by the publisher.
4.10 STRATEGY PATTERN
 A behavioral design pattern that lets you define a family of algorithms, put each of them into a
separate class, and makes their objects interchangeable.
 Context / Problem: How to design for varying, but related, algorithms or policies? How to
design for the ability to change (even dynamically) these algorithms or policies?
 Solution: Define each algorithm/policy/strategy in a separate class with a common interface.
 Example: Route Navigation Strategy-In our navigation app, each routing algorithm can be
extracted to its own class with a single buildRoute method. The method accepts an origin and
destination and returns a collection of the route’s checkpoints.
4.10.1 Strategy Pattern Representation
 The Context maintains a reference to one of the concrete strategies and communicates with this
object only via the strategy interface.
 The Strategy interface is common to all concrete strategies. It declares a method the context uses
to execute a strategy.
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 17
 Concrete Strategies implement different variations of an algorithm the context uses.
4.11 MAPPING DESIGN TO CODE
 In mapping the design to code implementation artifacts produced are source code, database
definition, JSP/XML/HTML pages and so forth
 The creation of code in an OO language – such as Java or c#- is not part of OOA/ D model-it’s
an end goal. The artifacts created in the Design Model provide some of the information
necessary to generate the code.
 Process: Write source code for
o Class and interface definitions
o Method definitions
 Design Class Diagrams contain class or interface names, classes, method and simple attributes.
 These are sufficient for basic class definitions.
 Elaborate from associations to add reference attributes.
4.11.1 Creating Class Definitions from DCDs
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 18
4.11.2 Creating Methods from Interaction Diagrams (Register.enterItem)
4.11.3 Collections
 One-to-many relationships are common. For example, a Sale must maintain visibility to a group
of many.
 SalesLineItem instances: In OO programming languages, these relationships are usually
implemented with the introduction of a collection object, such as a List or Map, or even a
simple array.
 Java libraries contain collection classes such as ArrayList and HashMap, which implement the
List and Map interfaces, respectively.
 The choice of collection class is influenced by the requirements.
o Key-based lookup requires the use of a Map,
o A growing ordered list requires a List, and so on.
4.11.4 Order ofImplementation
 Classes need to be implemented from least-coupled to most-coupled.
 Example:
o Possible first classes to implement are either Payment or ProductDescription;
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 19
o Next are classes only dependent on the prior implementations - ProductCatalog or
SalesLineItem.
How to design makeNewSale ?
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 20
enterItem
getTotal
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 21
makePayment, getBalance
Class Payment
// all classes are probably in a package named
// something like:
package com.foo.nextgen.domain;
public class Payment {
private Money amount;
public Payment( Money cashTendered ){ amount = cashTendered;
}
public Money getAmount() {
return amount;
}
}
Class ProductDescription
public class ProductDescription {
private ItemID id;
private Money price;
private String description;
public ProductDescription ( ItemID id, Money price, String description ) {
this.id = id; this.price = price;
this.description = description;
}
public ItemID getItemID() { return id; } public Money getPrice() { return price; }
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 22
public String getDescription() { return description; }
}
Class ProductCatalog
public class ProductCatalog {
private Map<ItemID, ProductDescription>
descriptions = new HashMap()<ItemID, ProductDescription>;
public ProductCatalog() {
// sample data
ItemID id1 = new ItemID( 100 ); ItemID id2 = new ItemID( 200 ); Money price = new Money( 3 );
ProductDescription desc;
desc = new ProductDescription( id1, price, "product 1" ); descriptions.put( id1, desc );
desc = new ProductDescription( id2, price, "product 2" ); descriptions.put( id2, desc );
}
public ProductDescription getProductDescription( ItemID id ) { return descriptions.get( id );
}
}
Class SalesLineItem
public class SalesLineItem
{
private ProductDescription description; private int quantity;
public SalesLineItem (ProductDescription desc, int quantity ) {
this.description = desc; this.quantity = quantity;
}
public Money getSubtotal() {
return description.getPrice().times( quantity );
}
}
Class Sale
public class Sale {
private List<SalesLineItem> lineItems = new ArrayList()<SalesLineItem>;
private Date date = new Date();
private boolean isComplete = false;
private Payment payment;
public Money getBalance(){
return payment.getAmount().minus( getTotal() );
}
public void becomeComplete() { isComplete = true; } public boolean isComplete() { return isComplete;
}
CS8592 Object Oriented Analysis and Design Unit IV
III IT Prepared by Kaviya.P, AP/IT Page 23
public void makeLineItem ( ProductDescription desc, int quantity ) {
lineItems.add( new SalesLineItem( desc, quantity ) );
}
public Money getTotal() {
Money total = new Money(); Money subtotal = null;
for ( SalesLineItem lineItem : lineItems ) {
subtotal = lineItem.getSubtotal(); total.add( subtotal );
}
return total;
}
public void makePayment( Money cashTendered ) {
payment = new Payment( cashTendered );
}
} //end of sale
Class Register
public class Register {
private ProductCatalog catalog; private Sale currentSale;
public Register( ProductCatalog catalog ) { this.catalog = catalog;}
public void makeNewSale() { currentSale = new Sale(); }
public void enterItem( ItemID id, int quantity ) {
ProductDescription desc = catalog.getProductDescription(id);
currentSale.makeLineItem( desc, quantity );
}
public void makePayment( Money cashTendered ) {
currentSale.makePayment( cashTendered );
}
public void endSale() { currentSale.becomeComplete(); }
}
Class Store
public class Store {
private ProductCatalog catalog = new ProductCatalog();
private Register register = new Register( catalog );
public Register getRegister() { return register; }
}

More Related Content

What's hot

Object oriented methodologies
Object oriented methodologiesObject oriented methodologies
Object oriented methodologies
naina-rani
 
Pressman ch-3-prescriptive-process-models
Pressman ch-3-prescriptive-process-modelsPressman ch-3-prescriptive-process-models
Pressman ch-3-prescriptive-process-models
saurabhshertukde
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
APU
 

What's hot (20)

Overview of UML Diagrams
Overview of UML DiagramsOverview of UML Diagrams
Overview of UML Diagrams
 
CS8592-OOAD Lecture Notes Unit-5
CS8592-OOAD Lecture Notes Unit-5 CS8592-OOAD Lecture Notes Unit-5
CS8592-OOAD Lecture Notes Unit-5
 
Uml class-diagram
Uml class-diagramUml class-diagram
Uml class-diagram
 
Ooad (object oriented analysis design)
Ooad (object oriented analysis design)Ooad (object oriented analysis design)
Ooad (object oriented analysis design)
 
CS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT IICS8592 Object Oriented Analysis & Design - UNIT II
CS8592 Object Oriented Analysis & Design - UNIT II
 
Object oriented methodologies
Object oriented methodologiesObject oriented methodologies
Object oriented methodologies
 
Sequence diagrams
Sequence diagramsSequence diagrams
Sequence diagrams
 
Object Oriented Analysis & Design
Object Oriented Analysis & DesignObject Oriented Analysis & Design
Object Oriented Analysis & Design
 
Ooad ppt
Ooad pptOoad ppt
Ooad ppt
 
Advanced Structural Modeling
Advanced Structural ModelingAdvanced Structural Modeling
Advanced Structural Modeling
 
Pressman ch-3-prescriptive-process-models
Pressman ch-3-prescriptive-process-modelsPressman ch-3-prescriptive-process-models
Pressman ch-3-prescriptive-process-models
 
Domain Modeling
Domain ModelingDomain Modeling
Domain Modeling
 
Object Oriented Modeling and Design with UML
Object Oriented Modeling and Design with UMLObject Oriented Modeling and Design with UML
Object Oriented Modeling and Design with UML
 
Unit 2(advanced class modeling & state diagram)
Unit  2(advanced class modeling & state diagram)Unit  2(advanced class modeling & state diagram)
Unit 2(advanced class modeling & state diagram)
 
Domain State model OOAD
Domain State model  OOADDomain State model  OOAD
Domain State model OOAD
 
Class diagram, use case and sequence diagram
Class diagram, use case and sequence diagramClass diagram, use case and sequence diagram
Class diagram, use case and sequence diagram
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagrams
 
Domain model Refinement
Domain model RefinementDomain model Refinement
Domain model Refinement
 
state modeling In UML
state modeling In UMLstate modeling In UML
state modeling In UML
 
7. sequence and collaboration diagrams
7. sequence and collaboration diagrams7. sequence and collaboration diagrams
7. sequence and collaboration diagrams
 

Similar to CS8592 Object Oriented Analysis & Design - UNIT IV

Patterns of Assigning Responsibilities
Patterns of Assigning ResponsibilitiesPatterns of Assigning Responsibilities
Patterns of Assigning Responsibilities
guest2a92cd9
 
Software Design Trilogy Part I - Responsibility Driven Design for Rubyists
Software Design Trilogy Part I - Responsibility Driven Design for RubyistsSoftware Design Trilogy Part I - Responsibility Driven Design for Rubyists
Software Design Trilogy Part I - Responsibility Driven Design for Rubyists
Andy Maleh
 
Creating a Use Case
Creating a Use Case                                               Creating a Use Case
Creating a Use Case
CruzIbarra161
 
06 styles and_greenfield_design
06 styles and_greenfield_design06 styles and_greenfield_design
06 styles and_greenfield_design
Majong DevJfu
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
CSEC5
 
Object oriented software engineering
Object oriented software engineeringObject oriented software engineering
Object oriented software engineering
Varsha Ajith
 

Similar to CS8592 Object Oriented Analysis & Design - UNIT IV (20)

DP PPTS by BK.pptx
DP PPTS by BK.pptxDP PPTS by BK.pptx
DP PPTS by BK.pptx
 
Bt8901 objective oriented systems1
Bt8901 objective oriented systems1Bt8901 objective oriented systems1
Bt8901 objective oriented systems1
 
Patterns of Assigning Responsibilities
Patterns of Assigning ResponsibilitiesPatterns of Assigning Responsibilities
Patterns of Assigning Responsibilities
 
Software Design Trilogy Part I - Responsibility Driven Design for Rubyists
Software Design Trilogy Part I - Responsibility Driven Design for RubyistsSoftware Design Trilogy Part I - Responsibility Driven Design for Rubyists
Software Design Trilogy Part I - Responsibility Driven Design for Rubyists
 
Object Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptxObject Oriented Programming using C++.pptx
Object Oriented Programming using C++.pptx
 
OOP ppt.pdf
OOP ppt.pdfOOP ppt.pdf
OOP ppt.pdf
 
Programming In C++
Programming In C++ Programming In C++
Programming In C++
 
Creating a Use Case
Creating a Use Case                                               Creating a Use Case
Creating a Use Case
 
Software_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptxSoftware_Engineering_Presentation (1).pptx
Software_Engineering_Presentation (1).pptx
 
OOSAD Chapter 6 Object Oriented Design.pptx
OOSAD Chapter 6 Object Oriented Design.pptxOOSAD Chapter 6 Object Oriented Design.pptx
OOSAD Chapter 6 Object Oriented Design.pptx
 
L12 GRASP
L12 GRASPL12 GRASP
L12 GRASP
 
06 styles and_greenfield_design
06 styles and_greenfield_design06 styles and_greenfield_design
06 styles and_greenfield_design
 
Unit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptxUnit No 6 Design Patterns.pptx
Unit No 6 Design Patterns.pptx
 
Unit 1 OOSE
Unit 1 OOSE Unit 1 OOSE
Unit 1 OOSE
 
TEST PPT
TEST PPTTEST PPT
TEST PPT
 
12266422.ppt
12266422.ppt12266422.ppt
12266422.ppt
 
Object Oriented Analysis and Design
Object Oriented Analysis and DesignObject Oriented Analysis and Design
Object Oriented Analysis and Design
 
Object oriented software engineering
Object oriented software engineeringObject oriented software engineering
Object oriented software engineering
 
Object Oriented Approach for Software Development
Object Oriented Approach for Software DevelopmentObject Oriented Approach for Software Development
Object Oriented Approach for Software Development
 
Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10Software Engineering with Objects (M363) Final Revision By Kuwait10
Software Engineering with Objects (M363) Final Revision By Kuwait10
 

More from pkaviya

BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdfBT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
pkaviya
 
OIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question BankOIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question Bank
pkaviya
 
CS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question BankCS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question Bank
pkaviya
 
CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V
pkaviya
 
CS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit IIICS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit III
pkaviya
 

More from pkaviya (20)

IT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database ConnectivityIT2255 Web Essentials - Unit V Servlets and Database Connectivity
IT2255 Web Essentials - Unit V Servlets and Database Connectivity
 
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdfIT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
IT2255 Web Essentials - Unit IV Server-Side Processing and Scripting - PHP.pdf
 
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and ScriptingIT2255 Web Essentials - Unit III Client-Side Processing and Scripting
IT2255 Web Essentials - Unit III Client-Side Processing and Scripting
 
IT2255 Web Essentials - Unit II Web Designing
IT2255 Web Essentials - Unit II  Web DesigningIT2255 Web Essentials - Unit II  Web Designing
IT2255 Web Essentials - Unit II Web Designing
 
IT2255 Web Essentials - Unit I Website Basics
IT2255 Web Essentials - Unit I  Website BasicsIT2255 Web Essentials - Unit I  Website Basics
IT2255 Web Essentials - Unit I Website Basics
 
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdfBT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
BT2252 - ETBT - UNIT 3 - Enzyme Immobilization.pdf
 
OIT552 Cloud Computing Material
OIT552 Cloud Computing MaterialOIT552 Cloud Computing Material
OIT552 Cloud Computing Material
 
OIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question BankOIT552 Cloud Computing - Question Bank
OIT552 Cloud Computing - Question Bank
 
CS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question BankCS8791 Cloud Computing - Question Bank
CS8791 Cloud Computing - Question Bank
 
CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V CS8592 Object Oriented Analysis & Design - UNIT V
CS8592 Object Oriented Analysis & Design - UNIT V
 
Cs8591 Computer Networks - UNIT V
Cs8591 Computer Networks - UNIT VCs8591 Computer Networks - UNIT V
Cs8591 Computer Networks - UNIT V
 
CS8591 Computer Networks - Unit IV
CS8591 Computer Networks - Unit IVCS8591 Computer Networks - Unit IV
CS8591 Computer Networks - Unit IV
 
CS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit IIICS8591 Computer Networks - Unit III
CS8591 Computer Networks - Unit III
 
CS8591 Computer Networks - Unit II
CS8591 Computer Networks - Unit II CS8591 Computer Networks - Unit II
CS8591 Computer Networks - Unit II
 
CS8591 Computer Networks - Unit I
CS8591 Computer Networks - Unit ICS8591 Computer Networks - Unit I
CS8591 Computer Networks - Unit I
 
IT8602 Mobile Communication - Unit V
IT8602 Mobile Communication - Unit V IT8602 Mobile Communication - Unit V
IT8602 Mobile Communication - Unit V
 
IT8602 - Mobile Communication Unit IV
IT8602 - Mobile Communication   Unit IV IT8602 - Mobile Communication   Unit IV
IT8602 - Mobile Communication Unit IV
 
IT8602 Mobile Communication - Unit III
IT8602 Mobile Communication  - Unit IIIIT8602 Mobile Communication  - Unit III
IT8602 Mobile Communication - Unit III
 
IT8602 Mobile Communication Unit II
IT8602 Mobile Communication   Unit II IT8602 Mobile Communication   Unit II
IT8602 Mobile Communication Unit II
 
IT8602 Mobile Communication Question Bank
IT8602 Mobile Communication Question BankIT8602 Mobile Communication Question Bank
IT8602 Mobile Communication Question Bank
 

Recently uploaded

XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
ssuser89054b
 

Recently uploaded (20)

Thermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - VThermal Engineering-R & A / C - unit - V
Thermal Engineering-R & A / C - unit - V
 
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
457503602-5-Gas-Well-Testing-and-Analysis-pptx.pptx
 
A Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna MunicipalityA Study of Urban Area Plan for Pabna Municipality
A Study of Urban Area Plan for Pabna Municipality
 
Design For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the startDesign For Accessibility: Getting it right from the start
Design For Accessibility: Getting it right from the start
 
Hostel management system project report..pdf
Hostel management system project report..pdfHostel management system project report..pdf
Hostel management system project report..pdf
 
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 
Online food ordering system project report.pdf
Online food ordering system project report.pdfOnline food ordering system project report.pdf
Online food ordering system project report.pdf
 
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced LoadsFEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
FEA Based Level 3 Assessment of Deformed Tanks with Fluid Induced Loads
 
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptxS1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
S1S2 B.Arch MGU - HOA1&2 Module 3 -Temple Architecture of Kerala.pptx
 
Computer Networks Basics of Network Devices
Computer Networks  Basics of Network DevicesComputer Networks  Basics of Network Devices
Computer Networks Basics of Network Devices
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
Ghuma $ Russian Call Girls Ahmedabad ₹7.5k Pick Up & Drop With Cash Payment 8...
 
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using PipesLinux Systems Programming: Inter Process Communication (IPC) using Pipes
Linux Systems Programming: Inter Process Communication (IPC) using Pipes
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
NO1 Top No1 Amil Baba In Azad Kashmir, Kashmir Black Magic Specialist Expert ...
 
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptxHOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
HOA1&2 - Module 3 - PREHISTORCI ARCHITECTURE OF KERALA.pptx
 
Introduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdfIntroduction to Data Visualization,Matplotlib.pdf
Introduction to Data Visualization,Matplotlib.pdf
 
Employee leave management system project.
Employee leave management system project.Employee leave management system project.
Employee leave management system project.
 

CS8592 Object Oriented Analysis & Design - UNIT IV

  • 1. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 1 CS8592 – Object Oriented Analysis and Design UNIT IV – Design Patterns 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 4.1 GRASP: DESIGNING OBJECTS WITH RESPONSIBILITIES General Responsibility Assignment Software Patterns (or Principles), abbreviated GRASP, consist of guidelines for assigning responsibility to classes and objects in object-oriented design. Responsibility in software is a very important concept and not only concerns classes but also modules and entire systems.  What is the responsibility of this class/module/component/system?  Is it responsible for this or is it responsible for that?  Is Single Responsibility Principle violated in this particular context? Reference Code:
  • 2. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 2 Doing and Knowing Doing responsibility of an object is seen as: a) Doing something itself – create an object, process data, do some computation/calculation b) Initiate and coordinate actions with other objects Knowing responsibility of an object can be defined as: a) Private and public object data b) Related objects references c) Things it can derive The list of 9 GRASP patterns (sometimes called principles but please, do not focus on naming here): Every programmer and designer should be familiar with these patterns and what is more important – know how to apply them in everyday work. 1. Information Expert 2. Creator 3. Controller 4. Low Coupling 5. High Cohesion 6. Indirection 7. Polymorphism 8. Pure Fabrication 9. Protected Variations 4.1.1 Information Expert Problem: What is a basic principle by which to assign responsibilities to objects? Solution: Assign a responsibility to the class that has the information needed to fulfill it. In following example Customer class has references to all customer Orders so it is natural candidate to take responsibility of calculating total value of orders: 4.1.2 Creator The goal is to define the creator object. Problem: Who creates object A? Solution: Assign class B the responsibility to create object A if one of these is true more is better) – B contains or compositely aggregates A – B records A – B closely uses A
  • 3. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 3 – B has the initializing data for A 4.1.3 Controller Problem: What first object beyond the UI layer receives and coordinates ―controls‖ a system operation? Solution: Assign the responsibility to an object representing one of these choices:  Represents the overall ―system‖, ―root object‖, device that the software is running within, or a major subsystem (these are all variations of a facade controller)  Represents a use case scenario within which the system operation occurs (a use case or session controller)  This principle implementation depends on high level design of our system but general we need always define object which orchestrate our business transaction processing. 4.1.4 Low Coupling Problem: How to reduce the impact of change? How to support low dependency and increased reuse? Solution: Assign responsibilities so that (unnecessary) coupling remains low. Use this principle to evaluate alternatives. Coupling is a measure how one element is related to another. The higher the coupling, the greater the dependence of one element to another. Low coupling means our objects are more independent and isolated.
  • 4. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 4 4.1.5 High Cohesion Problem: How to keep objects focused, understandable, manageable and as a side effect support Low Coupling? Solution: Assign a responsibility so that cohesion remains high. Use this to evaluate alternatives. Cohesion is a measure how strongly all responsibilities of the element are related. In other words, what is the degree to which the parts inside an element belong together. Classes with low cohesion have unrelated data and/or unrelated behaviors. For example, the Customer class has high cohesion because now it does only one thing – manage the Orders. 4.1.6 Indirection Problem: Where to assign a responsibility to avoid direct coupling between two or more things? Solution: Assign the responsibility to an intermediate object to mediate between other components or services so that they are not directly coupled. The indirection pattern supports low coupling and reuse potential between two elements by assigning the responsibility of mediation between them to an intermediate object. This ensures that coupling between them remains low.
  • 5. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 5 4.1.7 Polymorphism Problem: How handle alternatives based on type? Solution: When related alternatives or behaviors vary by type (class), assign responsibility for the behavior (using polymorphism operations) to the types for which the behavior varies. Polymorphism is fundamental principle of Object-Oriented Design. In this context, principle is strongly connected with (among others) Strategy Pattern. Polymorphism implies using operations in different ways, depending upon the instance they are operating upon. Polymorphism allows objects with different internal structures to have a common external interface. Polymorphism is particularly effective while implementing inheritance. By sending message to the Shape object, a call will be made to the corresponding sub class object – Circle or Triangle. 4.1.8 Pure Fabrication Problem: What object should have the responsibility, when you do not want to violate High Cohesion and Low Coupling but solutions offered by other principles are not appropriate? Solution: Assign a highly cohesive set of responsibilities to an artificial or convenience class that does not represent a problem domain concept. For example, in e-commerce systems we often have needed to convert one currency to another. Sometimes it is hard to say where this behavior should be placed so the best option is to create new class and interface. 4.1.9 Protected Variations Problem: How to design objects, subsystems and systems so that the variations or instability in these elements does not have an undesirable impact on other elements? Solution: Identify points of predicted variation or instability; assign responsibilities to create a stable interface around them. This is the most important principle which is indirectly related to the rest GRASP principles. Currently, one of the most important software metrics is the ease of change. As architects and programmers we must be ready for ever-changing requirements.
  • 6. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 6 4.2 DESIGN PATTERNS  Pattern is a named description of a problem and solution that can be applied to new context.  Software Pattern provides a generable reusable solution to a common reusable design problem and it guides the assignment of responsibilities to objects.  It shows the relationships and interactions between classes (or) objects.  Object Design is the process of adding details to the requirement analysis and making implementation decision.  Activities of object design are – Start Coding immediately – Start some UML modeling for object design – Start with another modeling technique such as CRC cards. 4.2.1 Software Patterns  Software Patterns consists of four parts in it  Pattern Name  Problem  Solution  Consequences  Example – Pattern Name-Information Expert – Problem-What is the basic principle to assign responsibilities to objects? – Solution- Assign a responsibility to the class that has the information needed to fulfill it. – Consequences-What other objects will be affected by assigning responsibilities to an object? 4.2.2 Refactoring  Refactoring is a systematic process of improving code without creating new functionality that can transform a mess into clean code and simple design.  Clean code is code that is easy to read, understand and maintain. Clean code makes software development predictable and increases the quality of a resulting product.  Performing refactoring step-by-step and running tests after each change are key elements of refactoring that make it predictable and safe. 4.3 THE “GANG OF FOUR” (GOF) DESIGN PATTERNS  Design Patterns: Elements of Reusable Object-Oriented Software (1994) is a software engineering book describing software design patterns. The book was written by four authors chapters describing 23 classic software design patterns.  Four authors: Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides  Patterns suggest opportunities for reuse in analysis, design and programming 4.3.1 Three Types ofPatterns  Creational Patterns (5 Types): Dealwith initializing and configuring classes and objects.  Structural Patterns (7 Types): Dealwith decoupling interface and implementation of classes and objects. Composition of classes or objects.
  • 7. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 7  Behavioral patterns (11 Types): Dealwith dynamic interactions classes and objects. How they distribute responsibility. 4.3.2 Creational Patterns  Abstract Factory: Factory for building related objects  Builder: Factory for building complex objects incrementally  Factory Method: Method in a derived class creates associates  Prototype: Factory for cloning new instances from a prototype  Singleton: Factory for a singular (sole) instance 4.3.3 Structural Patterns  Adapter: Translator adapts a server interface for a client  Bridge: Abstraction for binding one of many implementations  Composite: Structure for building recursive aggregations  Decorator: Decorator extends an object transparently  Facade: Simplifies the interface for a subsystem  Flyweight: Many fine-grained objects shared efficiently.  Proxy: One object approximates another 4.3.4 Behavioral Patterns  Observer: Dependents update automatically when subject changes  State: Object whose behavior depends on its state  Strategy: Abstraction for selecting one of many algorithms  Template Method: Algorithm with some steps supplied by a derived class  Visitor: Operations applied to elements of a heterogeneous object structure 4.4 FACTORYMETHOD PATTERN  A creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.  This is also called as Simple Factory or Concrete Factory.  Problem: Who should be responsible for creating objects when there are special considerations such as complex creation logic, a desire to separate creation responsibilities for better cohesion, etc.?  Solution: Create a Pure Fabrication object called a Factory that handles the creation.  A Factory Pattern or Factory Method Pattern says that just define an interface or abstract class for creating an object but let the subclassesdecide which class to instantiate. In other words, subclasses are responsible to create the instance of the class.  For example,both Truck and Ship classes should implement the Transport interface, which declares a method called deliver.  Each class implements this method differently: trucks deliver cargo by land, ships deliver cargo by sea.  The factory method in the RoadLogistics class returns truck objects, whereas the factory method in the SeaLogistics class returns ships.
  • 8. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 8  Merits and Demerits of Factory Pattern Method o Merits – The code becomes flexible and loosely coupled – The client code deals only with factory interface. Hence if new object is required then it can be added without disturbing the client code. – Can return same instance multiple times – Brings consistency in the code o Demerits – The class has to be refactored – Sub class needs to provide reimplementation for all factory methods – Code becomes complex 4.5 ABSTRACT FACTORY PATTERN  A creational design pattern that lets you produce families of related objects without specifying their concrete classes.  A factory is a class that returns products of a particular kind.  Declare the Abstract Factory an interface with a list of creation methods for all products that are part of the product family
  • 9. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 9  For each variant of a product family, we create a separate factory class based on the AbstractFactory interface.  Example: The ModernFurnitureFactory can only create ModernChair, ModernSofa and ModernCoffeeTable objects.  The client code has to work with both factories and products via their respective abstract interfaces.  This lets you change the type of a factory that you pass to the client code, as well as the product variant that the client code receives, without breaking the actual client code.  Example-Next Gen POS System for Abstract Factory Pattern 4.6 SINGLETON PATTERN  A creational design pattern that lets you ensure that a class has only one instance, while providing a global access point to this instance.  Problem: Exactly one instance of a class is allowed. Objects need a global and single point of access.  Solution: Define a static method of the class that returns the singleton: getInstance()  Singleton supports global visibility or a single access point to a single instance. 4.6.1 Implementations ofthe Singleton  Make the default constructor private, to prevent other objects from using the new operator with the Singleton class.  Create a static creation method that acts as a constructor. Under the hood, this method calls the private constructor to create an object and saves it in a static field. All following calls to this method return the cached object.  In singleton pattern getInstance method is frequently used. ServicesFactory accountingAdapter : IAccountingAdapter inventoryAdapter : IInventoryAdapter taxCalculatorAdapter : ITaxCalculatorAdapter getAccountingAdapter() : IAccountingAdapter getInventoryAdapter() : IInventoryAdapter getTaxCalculatorAdapter() : ITaxCalculatorAdapter ... note that the factory methods return objects typed to an interface rather than a class, so that the factory can return any implementation of the interface if ( taxCalculatorAdapter == null ) { // a reflective or data-driven approach to finding the right class: read it from an // external property String className = System.getProperty( "taxcalculator.class.name" ); taxCalculatorAdapter = (ITaxCalculatorAdapter) Class.forName( className ).newInstance(); } return taxCalculatorAdapter;
  • 10. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 10  Example: The database connection class acts as a Singleton. This class doesn’t have a public constructor, so the only way to get its object is to call the getInstance method. This method caches the first created object and returns it in all subsequent calls. class Singleton { public: static Singleton* getInstance(); protected: //Why are the following protected? Singleton(); Singleton(const Singleton&); Singleton& operator= (const Singleton&); private: static Singleton* instance; }; Singleton *p2 = p1->getInstance(); 4.6.2 Merits ofSingleton Pattern  It provides controlled access to sole instance.  It permits the refinement of operations and representations.  It is useful when only one instance of class must be created and accessible to clients from well- known access point. 4.7 ADAPTER PATTERN  A structural design pattern that allows objects with incompatible interfaces to collaborate.  Problem: How to resolve incompatible interfaces or how to 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.  Note: The Adapter pattern is an application of Polymorphism. Adapter pattern follows GRASP principles: Polymorphism, Protected Variation, Indirection.  Adapters cannot only convert data into various formats but can also help objects with different interfaces collaborate. Here’s how it works: o The adapter gets an interface, compatible with one of the existing objects. o Using this interface, the existing object can safely call the adapter’s methods. o Upon receiving a call, the adapter passes the request to the second object, but in a format and order that the second object expects.
  • 11. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 11  Example: When you travel from the US to Europe for the first time, you may get a surprise when trying to charge your laptop. The power plug and sockets standards are different in different countries. That’s why your US plug won’t fit a German socket. The problem can be solved by using a power plug adapter that has the American-style socket and the European-style plug.  In the adapter pattern example given for NextGen POS System iAccountingAdapter(incompatible) interface has to send values to intermediate adapter  iCreditcardAuthorizationService(compatible) adapter.  See figure for conceptual connection among GRASP principles and Adapter pattern
  • 12. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 12 4.7.1 Relating Adapter Pattern to GRASP Principles 4.7.2 Merits of Adapter Pattern  Merits o Two compatible objects or classes can be interfaced using adapter patterns o Reduces coupling between the objects o If we have several modules implementing same functionality then write adapters for them, the adapters are implementing the same interface  Demerits o It makes the code complex and difficult to debug. 4.8 BRIDGE PATTERN  A structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.  Problem: Occurs when extending classes of similar type  Solution: The Bridge pattern attempts to solve this problem by switching from inheritance to the object composition. What this means is that you extract one of the dimensions into a separate class hierarchy, so that the original classes will reference an object of the new hierarchy, instead of having all of its state and behaviors within one class.  Example: We can extract the color-related code into its own class with two subclasses: Red and Blue.  The Shape class then gets a reference field pointing to one of the color objects.  Now the shape can delegate any color-related work to the linked color object.  That reference will act as a bridge between the Shape and Color classes.
  • 13. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 13  From now on, adding new colors won’t require changing the shape hierarchy, and vice versa. 4.8.1 Bridge Pattern Representation  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.
  • 14. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 14 4.8.2 Merits and Demerits ofBridge Pattern  Merits o Separates the implementation from interface o It can be used when the class vary quite often o It is useful in graphic toolkits that need to run on multiple platforms o Implementation details can be effectively hidden from the client so that client focus an just the behavior desired  Demerits o Due to separation of interface and implementation it increases the complexity of client program o Performance of overall code is decreased 4.8.3 Difference between Bridge and Adapter Pattern Bridge Pattern Adapter Pattern Bridge pattern is used to decouple an abstraction class from its implementation. Converts the interface between the classes with less inheritance. Used when class vary quite often. Used to make existing classes to work with other without modifying their source code. Used in graphics toolkit. Used when two incompatible interfaces need to work together. Implementation details can be hidden from the client. Adapter acts as translator between two types. 4.9 OBSERVER PATTERN  A behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.  Problem: Different kinds of subscriber objects are interested in the state changes or events of a publisher object, and want to react in their own way when the publisher generates the event.  Solution: Define a ―subscriber‖ or ―listener‖ interface. Subscribers implement this interface. The publisher can dynamically register subscribers who are interested in an event, and notify them when an event occurs.  Example:
  • 15. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 15  The object that has some interesting state is often called subject, but since it’s also going to notify other objects about the changes to its state, we’ll call it publisher.  All other objects that want to track changes to the publisher’s state are called subscribers.  The Observer pattern suggests that you add a subscription mechanism to the publisher class so individual objects can subscribe to or unsubscribe from a stream of events coming from that publisher.  Publisher generates events and subscriber can subscribe or unsubscribe to that particular event. Publisher can have n number of subscribers.  Publisher notifies by calling the specific notification method on their objects to it’s subscribers 4.9.1 Observer Pattern Representation  The Publisher issues events of interest to other objects. These events occur when the publisher changes its state or executes some behaviors.  When a new event happens, the publisher goes over the subscription list and calls the notification method declared in the subscriber interface on each subscriber object.
  • 16. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 16  The Subscriber interface declares the notification interface. In most cases, it consists of a single update method.  Concrete Subscribers perform some actions in response to notifications issued by the publisher. 4.10 STRATEGY PATTERN  A behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and makes their objects interchangeable.  Context / Problem: How to design for varying, but related, algorithms or policies? How to design for the ability to change (even dynamically) these algorithms or policies?  Solution: Define each algorithm/policy/strategy in a separate class with a common interface.  Example: Route Navigation Strategy-In our navigation app, each routing algorithm can be extracted to its own class with a single buildRoute method. The method accepts an origin and destination and returns a collection of the route’s checkpoints. 4.10.1 Strategy Pattern Representation  The Context maintains a reference to one of the concrete strategies and communicates with this object only via the strategy interface.  The Strategy interface is common to all concrete strategies. It declares a method the context uses to execute a strategy.
  • 17. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 17  Concrete Strategies implement different variations of an algorithm the context uses. 4.11 MAPPING DESIGN TO CODE  In mapping the design to code implementation artifacts produced are source code, database definition, JSP/XML/HTML pages and so forth  The creation of code in an OO language – such as Java or c#- is not part of OOA/ D model-it’s an end goal. The artifacts created in the Design Model provide some of the information necessary to generate the code.  Process: Write source code for o Class and interface definitions o Method definitions  Design Class Diagrams contain class or interface names, classes, method and simple attributes.  These are sufficient for basic class definitions.  Elaborate from associations to add reference attributes. 4.11.1 Creating Class Definitions from DCDs
  • 18. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 18 4.11.2 Creating Methods from Interaction Diagrams (Register.enterItem) 4.11.3 Collections  One-to-many relationships are common. For example, a Sale must maintain visibility to a group of many.  SalesLineItem instances: In OO programming languages, these relationships are usually implemented with the introduction of a collection object, such as a List or Map, or even a simple array.  Java libraries contain collection classes such as ArrayList and HashMap, which implement the List and Map interfaces, respectively.  The choice of collection class is influenced by the requirements. o Key-based lookup requires the use of a Map, o A growing ordered list requires a List, and so on. 4.11.4 Order ofImplementation  Classes need to be implemented from least-coupled to most-coupled.  Example: o Possible first classes to implement are either Payment or ProductDescription;
  • 19. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 19 o Next are classes only dependent on the prior implementations - ProductCatalog or SalesLineItem. How to design makeNewSale ?
  • 20. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 20 enterItem getTotal
  • 21. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 21 makePayment, getBalance Class Payment // all classes are probably in a package named // something like: package com.foo.nextgen.domain; public class Payment { private Money amount; public Payment( Money cashTendered ){ amount = cashTendered; } public Money getAmount() { return amount; } } Class ProductDescription public class ProductDescription { private ItemID id; private Money price; private String description; public ProductDescription ( ItemID id, Money price, String description ) { this.id = id; this.price = price; this.description = description; } public ItemID getItemID() { return id; } public Money getPrice() { return price; }
  • 22. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 22 public String getDescription() { return description; } } Class ProductCatalog public class ProductCatalog { private Map<ItemID, ProductDescription> descriptions = new HashMap()<ItemID, ProductDescription>; public ProductCatalog() { // sample data ItemID id1 = new ItemID( 100 ); ItemID id2 = new ItemID( 200 ); Money price = new Money( 3 ); ProductDescription desc; desc = new ProductDescription( id1, price, "product 1" ); descriptions.put( id1, desc ); desc = new ProductDescription( id2, price, "product 2" ); descriptions.put( id2, desc ); } public ProductDescription getProductDescription( ItemID id ) { return descriptions.get( id ); } } Class SalesLineItem public class SalesLineItem { private ProductDescription description; private int quantity; public SalesLineItem (ProductDescription desc, int quantity ) { this.description = desc; this.quantity = quantity; } public Money getSubtotal() { return description.getPrice().times( quantity ); } } Class Sale public class Sale { private List<SalesLineItem> lineItems = new ArrayList()<SalesLineItem>; private Date date = new Date(); private boolean isComplete = false; private Payment payment; public Money getBalance(){ return payment.getAmount().minus( getTotal() ); } public void becomeComplete() { isComplete = true; } public boolean isComplete() { return isComplete; }
  • 23. CS8592 Object Oriented Analysis and Design Unit IV III IT Prepared by Kaviya.P, AP/IT Page 23 public void makeLineItem ( ProductDescription desc, int quantity ) { lineItems.add( new SalesLineItem( desc, quantity ) ); } public Money getTotal() { Money total = new Money(); Money subtotal = null; for ( SalesLineItem lineItem : lineItems ) { subtotal = lineItem.getSubtotal(); total.add( subtotal ); } return total; } public void makePayment( Money cashTendered ) { payment = new Payment( cashTendered ); } } //end of sale Class Register public class Register { private ProductCatalog catalog; private Sale currentSale; public Register( ProductCatalog catalog ) { this.catalog = catalog;} public void makeNewSale() { currentSale = new Sale(); } public void enterItem( ItemID id, int quantity ) { ProductDescription desc = catalog.getProductDescription(id); currentSale.makeLineItem( desc, quantity ); } public void makePayment( Money cashTendered ) { currentSale.makePayment( cashTendered ); } public void endSale() { currentSale.becomeComplete(); } } Class Store public class Store { private ProductCatalog catalog = new ProductCatalog(); private Register register = new Register( catalog ); public Register getRegister() { return register; } }