0% found this document useful (0 votes)
139 views86 pages

Unit Iv Design Patterns

The document discusses design patterns and principles for assigning responsibilities to objects in object-oriented design. It describes two types of responsibilities - "doing" and "knowing". Common responsibility patterns discussed include Creator, which assigns the responsibility of object creation, Information Expert, which assigns a responsibility to the class with the necessary information to fulfill it, and Controller, which assigns the responsibility of handling system events. The document provides examples of applying these patterns in a point-of-sale system design.

Uploaded by

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

Unit Iv Design Patterns

The document discusses design patterns and principles for assigning responsibilities to objects in object-oriented design. It describes two types of responsibilities - "doing" and "knowing". Common responsibility patterns discussed include Creator, which assigns the responsibility of object creation, Information Expert, which assigns a responsibility to the class with the necessary information to fulfill it, and Controller, which assigns the responsibility of handling system events. The document provides examples of applying these patterns in a point-of-sale system design.

Uploaded by

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

UNIT IV

DESIGN PATTERNS
Designing Objects with Responsibilities
Fundamental activity in OOD:
Assigning responsibilities to objects!
• Responsibility – collection of objects in term
of its behavior. (Reflects behavior of an
objects which are grouped into classes.
• Two types of responsibilities:
– Doing
– Knowing
Responsibilities
Two types of responsibilities:
1. Doing:
• Doing something itself such as creating an object
• doing a calculation
• initiating action in other objects
• Controlling and coordinating activities in other objects
2. Knowing:
• knowing about private encapsulated data
• knowing about related objects
• knowing about things it can derive or calculate
Note: “knowing” often found in domain model, e.g.
attributes and associations
Responsibilities
Responsibilities are more general than methods
• Methods are implemented to fulfill
responsibilities (Responsibilities are
implemented using methods.)
• Example: Sale class may define a method such
as getTotal() to know its total but may require
interaction with other objects say sending
getSubTotal() message to each SalesLineItem
object asking for its subtotal.
Example: POS (Point of Sale) System

Sales SalesLineItem

makeLineItem(Quantity)

Create (Quantity)

getTotal()

getSubTotal()
Example: ATM Banking System

:Customer :AtmSystem :BankDB

Create()

Enteramount()
Create()

getBalance()

returnBalance

Amount<balance?
Responsibility-Driven Design (RDD)
RDD is a metaphor for thinking about OO
software design.
Metaphor – software objects thought of as
people with responsibilities who collaborate
to get work done
An OO design as a community of collaborating
responsible objects
PATTERNS
Pattern – a named and well-known
problem/solution pair that can be applied in new
contexts, with advice on how to apply it in new
situations and discussion of its trade-offs,
implementations, variations, etc.

Many Patterns focus upon particular category of


the
problem and guide the developer about the
responsibilities that can be assigned to the object.
GRASP
• General Responsibility Assignment Software
Patterns (or Principles)
• Consists of guidelines required for assigning
responsibility to classes and objects in OO
design
• GRASP principles – a learning aid for OO
design with responsibilities
GRASP Principles
GRASP principles:
1. Creator
2. Information Expert
3. Controller
4. Low Coupling
5. High Cohesion
Creator
Creation of an object - most important activity

Problem: Who should be responsible for creating a new instance


of a class?

Solution: Assign class B the responsibility to create an instance


of class A if one or more of the following is true:
– B Aggregates A
– B contains A objects
– B records instances of A objects
– B closely uses A objects
– B has the initializing data that will be passed to A when it is created.
Create (book) Book
Catalog
Creator
Example: In POS System, Who should be responsible for
creating a new SalesLineItem instance?
Start with domain model:
Sale

time

Contains

1..*
Product
Sales Description
LineItem * Described-by 1
description
quantity price
itemID
Since a Sale contains SalesLineItem objects it should be
responsible according to the Creator Pattern

: Register : Sale

makeLineItem(quantity)
create(quantity) : SalesLineItem
Creator
Benefits:
• Supports Low Coupling – Less Dependency
between objects and objects become reusable.
Related design pattern:
– Factory for more complex creation situations
(GoF – Gang of Four Patterns)
– Low Coupling
– Aggregation and Composition
Information Expert
Problem: What is a general principle for assigning
responsibilities to objects?

Solution: Assign a responsibility to the information


expert, that is, the class that has the information
necessary to fulfill the responsibility.

Example: (from POS system) Who should be


responsible for knowing the grand total of a sale?
Information Expert
Example: (from POS system) Who should be
responsible for knowing the grand total of a
sale?
Start with domain model and look for
associations with Sale
What information is necessary to calculate
grand total and which objects have the
information?
Sale

time

Contains

1..*
Product
Sales Description
LineItem * Described-by 1
description
quantity price
itemID

Here Sale Contains SalesLineItems” so it has the information


necessary for total .
How is line item subtotal determined?
quantity – an attribute of SalesLineItem
price – stored in ProductDescription . . .

this notation will imply we


are iterating over all
elements of a collection Sale

time
...
t = getTotal 1 *: st = getSubtotal lineItems[ i ] :
: Sale getTotal()
SalesLineItem

SalesLineItem

quantity

New method getSubtotal()


Benefits:
• Supports Information Encapsulation
• Supports Low Coupling
• Behavior is distributes across classes. So it helps
designing light weight class definition
• Supports High Cohesion
Related Patterns:
• Low Coupling
• High Cohesion
Controller
Problem: Who should be responsible for handling a
system event? (Or, what object receives and
coordinates a system operation?)

Solution: Assign the responsibility for receiving and/or


handling a system event to one of following choices:
– Object that represents overall system, device or
subsystem (façade controller)
– Object that represents a use case scenario within which
the system event occurs (Usecase Controller or Usecase
Handler)
Controller
Input system event – event generated by an
external actor associated with a system
operation
Controller – a non-UI object responsible for
receiving or handling a system event
Façade Controller

presses button

: Cashier

actionPerformed( actionEvent )

UI Layer :SaleJFrame

system operation message


enterItem(itemID, qty)

Which class of object should be responsible for receiving this


Domain system event message?
: ???
Layer
It is sometimes called the controller or coordinator. It does not
normally do the work, but delegates it to other objects.

The controller is a kind of "facade" onto the domain layer from


the interface layer.
Controller
• Controller is a façade into domain layer from
interface layer
• Often use same controller class for all system
events of one use case so that one can
maintain state information, e.g. events must
occur in a certain order
• Normally controller coordinates activity but
delegates work to other objects rather than
doing work itself
Controller
• Façade controller representing overall system
– use when there aren’t many system events

• Use case controllers – different controller for


each use case
System Register

endSale() ...
enterItem()
makeNewSale() endSale()
makePayment() enterItem()
makeNewSale()
makeNewReturn() makePayment()
enterReturnItem()
... makeNewReturn()
enterReturnItem()
...

system operations allocation of system


discovered during system operations during design,
behavior analysis using one facade controller

ProcessSale HandleReturns
System Handler Handler

endSale() ... ...


enterItem()
makeNewSale() endSale() enterReturnItem()
makePayment() enterItem() makeNewReturn()
makeNewSale() ...
enterReturnItem() makePayment()
makeNewReturn()
...

allocation of system
operations during design,
using several use case
controllers
Controller
Bloated controller
– Single class receiving all system events and there
are many of them
– Controller performs many tasks rather than
delegating them
– Controller has many attributes and maintains
significant information about system which should
have been distributed among other objects
Worst Design

presses button

Cashier

actionPerformed( actionEvent )

It is undesirable for an interface


layer object such as a window to get
UI Layer :SaleJFrame involved in deciding how to handle
domain processes.

Business logic is embedded in the


presentation layer, which is not useful.

1: makeLineItem(itemID, qty)
Domain Layer :Sale

SaleJFrame should not


send this message.
Good Design

presses button

: Cashier

actionPerformed( actionEvent )

system operation message


UI Layer :SaleJFrame

1: enterItem(itemID, qty)

controller

Domain Layer 1.1: makeLineItem(itemID, qty)


:Register :Sale
Benefits:
• By delegating system operations responsibilities to the
controller, supports the concept of reusability
• Reasonable choice for occurring the system operations
in some sequence.
Related Patterns:
• Façade Patterns (GoF – Gang of Four Patterns) – Object
that provides interface in large sub system. (Overall
controller)
• Pure Fabrication (GRASP Patterns) – Who is
responsible when designers and developers don’t want
to violate low coupling and high cohesion.
• Indirection (GRASP Patterns) – How to assign
responsibility to various classes in order to avoid direct
coupling.
Low Coupling
Problem: How to support low dependency, low
change impact, increased reuse?
(How to reduce the impact of change)

Solution: Assign a responsibility so coupling is


low.

Coupling – a measure of how strongly one


element is connected to, has knowledge of, or
relies on other elements
Low Coupling
A class with high coupling relies on many other
classes – leads to problems:
– Changes in related classes force local changes
– Harder to understand in isolation
– Harder to reuse
Low Coupling
Worst Design (High Coupling)

makePayment() 1: create()
: Register p : Payment

2: addPayment(p)
:Sale

Good Design (Low Coupling)

makePayment() 1: makePayment()
: Register :Sale

1.1. create()

:Payment
Benefits:
• Impact of Changes can be reduced
• Objects can be understood easily in isolation
• Reusability of objects is convenient
High Cohesion
Problem: How to keep objects focused,
understandable and manageable. (How to
keep complexity manageable)

Solution: Assign the responsibility so that


cohesion remains high.

Cohesion – a measure of how strongly related


and focused the responsibilities of an element
(class, subsystem, etc.) are
High Cohesion
Problems from low cohesion (does many
unrelated things or does too much work):
– Hard to understand/comprehend
– Hard to reuse
– Hard to maintain
– Brittle – easily affected by change
High Cohesion
Example: (from POS system) Who should be
responsible for creating a Payment instance and
associate it with a Sale?

1. Register creates a Payment p then sends


addPayment(p) message to the Sale

makePayment() : Register 1: create() p : Payment

2: addPayment(p)
:Sale
High Cohesion
Register is taking on responsibility for system
operation makePayment()
– In isolation no problem
– But if we start assigning additional system
operations to Register then will violate high
cohesion
High Cohesion
Example: (from POS system) Who should be
responsible for creating a Payment instance and
associate it with a Sale?

2. Register delegates Payment creation to the Sale

makePayment() 1: makePayment()
: Register :Sale

1.1. create()

:Payment
Worst Design (Low Cohesion)

:Customer :AtmSystem

1Enteramount()

2. checkbalance()

3. Withdraw()
Good Design (High Cohesion)

:Customer :AtmSystem :Transaction :Bank

1. Enteramount()

2. Withdraw()

3. checkbalance()

4.returnbalance

5. amount<
6.Transaction balance?
Successful

7.Dispense Cash
High Cohesion
Typically high cohesion => few methods with
highly related functionality
Benefits of high cohesion:
– Easy to maintain
– Easy to understand
– Easy to reuse
DESIGN PATTERNS
• General reusable solutions to commonly occurring
problem in software design.
• Represent solutions to problems that arise when
developing software within a particular context
• Not a finished design – cannot be transformed
directly into code
• Description or Template that explains how to solve
the problems in various context.
• Describes
– Context in which pattern can be reused
– Forces within the context that patterns seek to resolve
– Suggested Solutions
Benefits:
• Design Reuse. (More powerful than code
reuse)
• Provides common vocabulary for design
• Make it easier for others to understand what
you did and why.
• Easy to transform application of one pattern
to an application of another.
GOF
• GOF – GANG OF FOUR
• Over 20 years ago the iconic computer science
book “
Design Patterns: Elements of Reusable Object-Ori
ented Software
” was first published. 
• The four authors of the book: Erich Gamma,
Richard Helm, Ralph Johnson, and John Vlissides,
have since been dubbed “The Gang of Four”. 
• It deals about 23 patterns
Types of Patterns
• Creational patterns:
– Deal with object creation mechanisms, trying to create
objects in a manner suitable to the situation
• Structural patterns:
– Deal with decoupling interface and implementation of
classes and objects
– Composition of classes or objects
• Behavioural patterns:
– Deal with dynamic interactions among societies of classes
and objects
– How they distribute responsibility
• creational
– factory method
• structural
– Bridge
– Adapter
• behavioural
–Strategy
– observer
Creational Design Patterns
• Design patterns that deal with object creation mechanisms,
trying to create objects in a manner suitable to the situation.
– Class Creational Patterns – Deals with class instantiation
– Object Creational Patterns – Deals with object creation..
• While class-creation patterns use inheritance effectively in the
instantiation process, object-creation patterns use delegation
effectively to get the job done.
Factory method
• In Java applications, you might be often using
the new operator to create an object of a class. 
• This is often fine for small Java programs.
• But when you work on large enterprise class
applications,
• It may have following difficulties
- the amount of code to create objects will
gradually increas
- the complexities of managing the code will
keep increasing
Abstract Factory
• Abstract Factory patterns work around a super-factory which
creates other factories.
• This factory is also called as factory of factories.
• Provides one of the best ways to create an object.
• Provide an interface for creating families of related or
dependent objects without specifying their concrete classes.
• Provide an interface for creating families of related or
dependent objects without specifying their concrete classes.
• · A hierarchy that encapsulates: many possible "platforms",
and the construction of a suite of "products".
• Provide a level of indirection that abstracts the creation of
families of related or dependent objects without directly
specifying their concrete classes.
• The "factory" object has the responsibility for providing
creation services for the entire platform family.
• Clients never create platform objects directly, they ask the
factory to do that for them.
• Create an interface for Shapes.
• Create concrete classes implementing the same interface.
• Create an interface for Colors.
• Create concrete classes implementing the same interface.
• Create an Abstract class to get factories for Color and Shape
Objects.
• Create Factory classes extending AbstractFactory to generate
object of concrete class based on given information.
• Create a Factory generator/producer class to get factories by
passing an information such as Shape or Color
• Use the FactoryProducer to get AbstractFactory in order to get
factories of concrete classes by passing an information such as
type.
Factory Method
• Create object without exposing the creation logic to the client and
refer to newly created object using a common interface.
• provides one of the best ways to create an object.
• One of the most used design patterns in java
• Define an interface for creating an object, but let subclasses decide
which class to instantiate. Factory Method lets a class defer
instantiation to subclasses.
• Defining a "virtual" constructor.
• A framework needs to standardize the architectural model for a
range of applications, but allow for individual applications to define
their own domain objects and provide for their instantiation.
• A superclass specifies all standard and generic behavior (using pure
virtual "placeholders" for creation steps), and then delegates the
creation details to subclasses that are supplied by the client.
• Factory Method makes a design more customizable and only a little
more complicated. Other design patterns require new classes,
whereas Factory Method only requires a new operation.
• The Factory Method defines an interface for creating objects, but
lets subclasses decide which classes to instantiate
• Factory Method is similar to Abstract Factory but without the
emphasis on families.
• Create an interface.
• Create concrete classes implementing the
same interface.
• Create a Factory to generate object of
concrete class based on given information.
• Use the Factory to get object of concrete class
by passing an information such as type.
• Client needs a product but instead of creating it directly, it
asks factory object for new product providing information
about the type of object it needs.
• Factory instantiates new concrete product and then returns
to the client the newly created product.
• Client uses the product as abstract product without being
aware about their concrete implementation.
• In our example, New Shapes can be added without changing
single line of code in framework
Structural Design Patterns
• Design patterns that ease the design by identifying a
simple way to realize relationships between entities.
• Example:
– Adapter Pattern: makes one interface (Adaptee’s)
conform to another
– Gives a uniform abstraction of different interfaces
– Class Adapter inherits privately from an Adaptee class
– Adapter then expresses its interface in terms of the
Adaptee’s.
Adapter Pattern
• Works as a bridge between two incompatible interfaces.
• Convert the interface of a class into another interface clients expect
• This pattern combines the capability of two independent interfaces.
• Interfaces may be incompatible but the inner functionality should suit the
need
• This pattern involves a single class which is responsible to join functionalities
of independent or incompatible interfaces.
• A real life example could be a case of card reader which acts as an adapter
between memory card and a laptop. You plugin the memory card into card
reader and card reader into the laptop so that memory card can be read via
laptop.
• Adapter is about creating an intermediary abstraction that translates, or
maps, the old component to the new system.
• Clients call methods on the Adapter object which redirects them into calls to
the legacy component. This strategy can be implemented either with
inheritance or with aggregation.
Example
• Create interfaces for Media Player and Advanced Media
Player.
• Create concrete classes implementing the
AdvancedMediaPlayer interface.
• Create adapter class implementing the MediaPlayer interface.
• Create concrete class implementing the MediaPlayer
interface.
• Use the AudioPlayer to play different types of audio formats.
• Object Adapter pattern
– The adapter contains an instance of the class it wraps. In this
situation, the adapter makes calls to the instance of the
wrapped object.
• Class Adapter pattern
– Uses multiple polymorphic interfaces implementing or
inheriting both the interface that is expected and the interface
that is pre-existing.
Object Adapter
Class Adapter
Bridge Pattern
• Decouple an abstraction from its implementation so that the
two can vary independently. (decouples implementation class
and abstract class by providing a bridge structure between
them)
• Provides an interface which acts as a bridge which makes the
functionality of concrete classes independent from interface
implementer classes.
• Both types of classes can be altered structurally without
affecting each other.
Example
• circle can be drawn in different colors using same abstract
class method but different bridge implementer classes.
• We have a DrawAPI interface which is acting as a bridge
implementer and concrete classes RedCircle, GreenCircle
implementing the DrawAPI interface.
• Shape is an abstract class and will use object of DrawAPI.
BridgePatternDemo will use Shape class to draw different
colored circle.
Behavioural Design Patterns
• Describes how a group of peer objects cooperate to
perform a task that can be carried out by itself.
• Captures how classes cooperate with their
subclasses to satisfy the task.

Example:
• Template Method: defines algorithms step by step.
• Each step can invoke an abstract method (that must
be defined by the subclass) or a base method.
• Subclass must implement specific behavior to
provide required services
Strategy Design Patterns
• Enables an algorithm's behavior to be selected
at runtime.
• Class behavior or its algorithm can be changed
at run time.
• Defines family of algorithms
• Encapsulates each algorithm
• Makes an algorithm interchangeable within that family.
• Strategy lets the algorithm vary independently
from clients that use it.
• Capture the abstraction in an interface, bury implementation
details in derived classes.
• For instance, a class that performs validation on incoming
data may use a strategy pattern to select a validation
algorithm based on the type of data, the source of the data,
user choice, or other factors.
• These factors are not known for each case until run-time, and
may require radically different validation to be performed.
• Encapsulate interface details in a base class, and
bury implementation details in derived classes.
• The interface captures the abstraction the
client wants to exercise, and the
implementations of that interface are
effectively hidden.
• Achieve high cohesion and low coupling
• we create objects which represent various
strategies and a context object whose
behavior varies as per its strategy object.
• The strategy object changes the executing
algorithm of the context object.
Observer Design Pattern
• Software design pattern in which an object, called the subject, maintains
a list of its dependents, called observers, and notifies them automatically
of any state changes, usually by calling one of their methods.
• Observer pattern is used when there is one-to-many relationship between
objects such as if one object is modified, its dependent objects are to be
notified automatically.
• Observer pattern falls under behavioral pattern category.
Intent:
– Define a one-to-many dependency between objects so that when one
object changes state, all its dependents are notified and updated
automatically.
– Encapsulate the core (or common or engine) components in a Subject
abstraction, and the variable (or optional or user interface)
components in an Observer hierarchy.
– The "View" part of Model-View-Controller.
• Define an object that is the "keeper" of the data model and/or business
logic (the Subject).
• Delegate all "view" functionality to decoupled and distinct Observer
objects.
• Observers register themselves with the Subject as they are created.
• Whenever the Subject changes, it broadcasts to all registered Observers
that it has changed, and each Observer queries the Subject for that subset
of the Subject's state that it is responsible for monitoring.
• This allows the number and "type" of "view" objects to be configured
dynamically, instead of being statically specified at compile-time.
• Subject represents the core (or independent or common or engine)
abstraction.
• Observer represents the variable (or dependent or optional or user
interface) abstraction.
• The Subject prompts the Observer objects to do their thing. Each
Observer can call back to the Subject as needed.
• Observer pattern uses three actor classes. Subject, Observer and Client.
• Subject is an object having methods to attach and detach observers to a
client object.
• We have created an abstract class Observer and a concrete class Subject
that is extending class Observer.
• ObserverPatternDemo class, will use Subject and concrete class object to
show observer pattern in action.
• Create Subject class.
• Create Observer class.
• Create concrete observer classes
• ObserverPatterDemo Class Use Subject and concrete observer objects.
Example Output:
First state change: 15
Hex String: F
Octal String: 17
Binary String: 1111
Second state change: 10
Hex String: A
Octal String: 12
Binary String: 1010
 
Mapping Design to Code
Shape.java
public interface Shape { // Add Code to declare draw() method }
Rectangle.java
public class Rectangle implements Shape {
// Add Code here to implement draw() method }
Square.java
public class Square implements Shape {
// Add Code here to implement draw() method }
Circle.java
public class Circle implements Shape { // Add Code Here }
Write the coding for color interface in similar manner
AbstractFactory.java
public abstract class AbstractFactory { // declare getColor() and
getShape() abstract methods }
ShapeFactory.java
public class ShapeFactory extends AbstractFactory {
// Add Code here to define getShape() and getColor() method }
ColorFactory.java
public class ColorFactory extends AbstractFactory {
//Add Code here to define getShape() and getColor() method }
FactoryProducer.java
public class FactoryProducer {
public static AbstractFactory getFactory(String choice) {
//Add Code to get the factory (Shape or Color) based on user choice }
}
AbstractFactoryPatternDemo.java
public class AbstractFactoryPatternDemo {
public static void main(String[] args) {
// Add Code for user to pass information such as type of factory (Shape or Color) }
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy