Unit Iv Design Patterns
Unit Iv Design Patterns
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
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.
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?
time
Contains
1..*
Product
Sales Description
LineItem * Described-by 1
description
quantity price
itemID
time
...
t = getTotal 1 *: st = getSubtotal lineItems[ i ] :
: Sale getTotal()
SalesLineItem
SalesLineItem
quantity
presses button
: Cashier
actionPerformed( actionEvent )
UI Layer :SaleJFrame
endSale() ...
enterItem()
makeNewSale() endSale()
makePayment() enterItem()
makeNewSale()
makeNewReturn() makePayment()
enterReturnItem()
... makeNewReturn()
enterReturnItem()
...
ProcessSale HandleReturns
System Handler Handler
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 )
1: makeLineItem(itemID, qty)
Domain Layer :Sale
presses button
: Cashier
actionPerformed( actionEvent )
1: enterItem(itemID, qty)
controller
makePayment() 1: create()
: Register p : Payment
2: addPayment(p)
:Sale
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)
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?
makePayment() 1: makePayment()
: Register :Sale
1.1. create()
:Payment
Worst Design (Low Cohesion)
:Customer :AtmSystem
1Enteramount()
2. checkbalance()
3. Withdraw()
Good Design (High Cohesion)
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) }
}