You are on page 1of 77

Behavioral patterns

 increase flexibility in carrying out communication among objects

Part-1
  Purpose
Creational Structural Behavioral

Interpreter
Class Factory Method Adapter
Template Method

Chain of Responsibility

Scope Adapter Command


Bridge Iterator
Abstract Factory Mediator
Composite
Builder
Object Prototype
Decorator Memento
Observer
Façade
Singleton State
Flyweight
Proxy Strategy
Visitor
Strategy Design Pattern
Do you use Strategies?
• We all have dealt with strategies in certain
moments of our life.
• In more technical words strategy is a set of
planned actions designed to achieve a specific
goal.
• Simply, you try out many strategies when a
final exam is close by.  collect photo copied
notes from friends, discussions for missed
lessons, watch some videos on YouTube and
many more creative strategies when the exams are
getting closer.
• Likewise, strategy design pattern provides
multiple solutions for a recurring problem in
the software world.
Objects are behaving
• As a norm in software design and development
world, isolated components are called as
objects.
• To build a successful system we need to have
many objects with the ability to communicate
and co-work with each other.
• But in most complex systems objects
interactions cause many issues.
• Behavioral design patterns provide solutions to this
object communication and interaction
problems.
Define Strategy Pattern
• Strategy design pattern is identified as a behavioral
design pattern since it directly controls the
object behaviors.
• This pattern is used to handle the software
algorithms, manage interactions and
responsibilities among objects to achieve a
specific task.
The GOF definition
Strategy pattern defines a family of algorithms,
encapsulate each one, and make them
interchangeable. Strategy lets the algorithm vary
independently from clients that use it.
How Strategy Pattern Works
• This pattern is most suitable when we have
multiple solutions to one problem.
• In a more technical way there are multiple
algorithms to achieve a specific task.
• Each algorithm is independent of one another and
enclosed with own implantation.
• But all of those algorithms is capable of
resolving that specific problem likewise
anyone can replace one algorithm from another
depending on their requirement.
• Algorithm content and implementation are
decoupled from the client who uses it and the
client can select any upon runtime based on
individual parameters and conditions.
Below figure describes the overall mechanism of the
strategy pattern.
What is Algorithm in Strategy Pattern?
 The algorithm is an individual strategy.
 Each algorithm should implement that common
interface which is enforced by an abstract strategy.
 Each individual strategy should have a unique
functionality that can be implemented as a
concrete strategy.
When to use the Strategy Pattern?
• When there are multiple solutions or ‘n’ number
of algorithms for a certain problem and we need all
of those to be available so that it is possible to make
a choice at runtime
• When you have different variants of one
algorithm to achieve any function, each variant can
enclose in a strategy
• When there are multiple related classes which
only differs from their behaviors, strategy pattern
can be used to dynamically select the required
behavior
• When the objects should have easy interaction
without getting tightly coupled with dependencies.
• When there are more private internal data to
hide from outside.
• If you need to avoid heavy conditional
statements those each behavior can be
encapsulated in a strategy.
Real World Example
Let’s take an item purchasing at a shopping mall.
Basic Steps to Perform
1. Customer comes to the cashier
2. System accepts customer details
3. System calculates bill amount
4. System apply discount based on day of the week
(This is where the strategy pattern comes into the
picture)
1. Monday – 10 %
2. Friday – 50 %
3. Other days – 0 %
5. System output the total bill for the customer
• System has to select which discount option assign to
the bill based on the day of the week
Problem – System has to apply discounts to bills

Solution – There are 3 options for discounts


based on days – system has to select one and
calculate the bill amount
High-Level Class Diagram for the Shopping
Mall Scenario
• Above figure contains the code samples for the main
interface and implementing concrete classes. The
rest of the class implementations are described later.
• Context – includes client or decision logic to
select the correct discount based on the
day.
.
Context Class
• This class bridges a client with the strategy keeping
a reference to the DiscountStrategy object. Hence,
the ShoppingMallContext class will be initialized
with a DiscountStrategy object in order to forward
the client’s request to the strategy.

ShoppingMallContext
Client Class
• This class is the main user of the functionality or the
particular algorithm. It requests the exact strategy
based on certain requirements and conditions. Client
class should first invoke the Context class in order
to grab the decided strategy at runtime.

Client Class
Advantages of Strategy Pattern
• This gives a greater flexibility and reuse
• It is possible to eliminate large conditional
statements using this pattern
• Since this is dynamic we don’t need to find
alternatives to painful hard coding
• Easier to maintain the different behaviors
since they are encapsulated in separate classes.
• There are wide variety of selections for same
behavior.
Challenges of Strategy Pattern
This will increase the number of objects in
the system which will lead to performance
issues later.
There will be additional operational cost
due to interaction between strategies and
their context.
• Strategy pattern gives you the ability to stay
independent and provide space for all
possible approaches to come into the play when
designing a software system.
• It is a great way to enhance the versatile
nature of a system.
Command Pattern
Command Pattern
• In this pattern an object is used to encapsulate
all information needed to perform an action or
trigger an event at a later time.
This information includes ......
The method name,
The object that owns the method and
Values for the method parameters.
The GoF definition
‘Encapsulate a request as an object, thereby letting
you parameterize clients with different requests,
queue or log requests, and support undo of
operations’
What is ‘Command’ Object?
• This is the intermediary object that links the
request invoker, which triggers the request and
the request receiver, which handle the
request by performing several operations.

• It does not execute any functionality but


contains all the information required to perform
an operation.
• Command object will contain only one method
called ‘execute()’ and it will trigger the actual
operations from request receiving end.
• In addition, this command object act as the main
interface for all the internal commands and a
sequence of command objects can be assembled into a
composite command.
• This materialization of commands as objects enable the
requests to perform passing, staging, sharing and treating
as table entries.
Structure of the Command Pattern:
Class Diagram
Components of the Command Pattern
1. Command

2. Concrete Command

3. Invoker
4. Receiver
5. Client
Command
• Represents the common interface for all concrete
commands. This is the core of the contract and must
contain the execute() equal method to pass the
trigger.
Concrete Command
• This class extends the command interface and
implements the execute() method with actual
operations to be performed in order to fulfil the
client request. It also creates a binding between
the action and the receiver. Often concrete command
uses the external object ‘Receiver’ to store and use
the required parameters to execute the methods.
Invoker
• This is the main entry point to execute a
complex set of commands.
• Client calls the invoker’s execute command method
to access the command interface. Invoker stores a
reference of a command object to trigger the
operation executed when required. It is unaware of
the concrete command and does not create any
command objects, but instruct the available
command object to carry out the request.
Receiver
• This object knows how to perform the actual
operations and carry out the actions to fulfil
the request. That means it contains the business
logic or data related to response creation.
Client
• The client instantiates a concrete command object
and passes those to appropriate invokers. It creates
the invoker and receiver objects as well. Then it
checks and decides which receiver objects link with
the command objects and which commands to link
with the invoker. In addition, it decides which
command to execute at which points
Command Pattern Example
• Let’s assume a smart home electrical unit
system that controls by a universal remote.
• There are two kinds of systems, which are
operated by the universal remote.
• Those two are the living room light system and
Air Conditioner. 
• We will include those two sub-systems into a
super system as ‘Home Electronics’.
• Universal remote has two buttons as ‘On’ and
‘Off’. When the homeowner press ‘On’ both the
light system and air-conditioned activates.
Let’s apply the command pattern to this
scenario,
• Command: Command interface to initiate the
execution and abstract the concrete commands.
• OnCommand: Concrete command class that
implements the ‘On’ operations for the
‘HomeElectronics’
• OffCommand: Concrete command class that
implements the ‘Off’ operations for the
‘HomeElectronics’
• UniversalRemote: UniversalRemote class will
maintain all the receivers and will provide a
method to identify the currently active
receiver.
• HomeElectronics: Parent class for ‘LightSystem’
and ‘Airconditioner’ home electronic systems.
• LightSystemReceiver: Act as a ‘Receiver’ object
for the scenario, contains actual method
implementations to execute the required functions.
• Air-condition Receiver: Act as the ‘Receiver’
object for the scenario, contains actual method
implementations to execute the required functions.
• Button Invoker: This class act as the invoker for
any action.
• Home Owner Client: The client who needs the
service of receivers.
How to Implement the Pattern in Example
• Define the base interface ‘Command’ with the ‘execute()’
similar method
• Create concrete classes implementing the ‘Command’
interface and including a ‘Receiver’ object instance with
appropriate arguments to perform the concrete execution
• Include an instance of ‘Command’ inside the ‘Invoker’
object
• The client creates the ‘Command’ and ‘Invoker’ instances
and passes a command instance to the invoker instance
• Then invoker decides and triggers the ‘execute()’ method
at the required time
• Finally, receivers get the signal and execute the actual
methods to cater the request
High-Level Diagram
When to use the Command Pattern
• When the requests need to be handled in certain
time occurrences and according to different
triggers situations.
• When the client and the service provider needs
to be decoupled.
• When there is a need for rollback
functionality for certain operations.
• When the history of requests required.

• When there is a need to add new commands.

• When there is a need for parameterizing


objects according to an action.
Code Samples
• Code Samples
• Code Samples
• Code Samples
• Code Samples
Visitor Design Pattern
What is Visitor Design Pattern?
• This pattern is useful when an object structure
contains different kinds of operations to use
in different situations.
• Elements of an object structure will be same
but the applied functionality may vary.
• Thus, there is no need to change any part of
classes of the objects to achieve the required
different operations.
• Also, this separation operation algorithm from
object structure increases the ability to add new
operations existent object structure without
modifying the structures. This is a way of
simplifying operations on the set of related objects.
The GoF definition
‘Represent an operation to be performed on the
elements of an object structure. The visitor pattern
lets you define a new operation without changing
the classes of the elements on which it operates.’
• As the definitions states, pattern preserves the
structure of the object, while incorporating a
variety of new operations performed on the object.
• This is most suitable when the operations are
changing frequently.
• In another way, pattern facilitates a way to separate
the varied algorithms on one object. By that way,
pattern adheres to the open/closed principle as well.
What is Visitor?
• Pattern uses a separate component called
‘Visitor’ to incorporate that ability to the class
hierarchy.
• The visitor lets the developer define new
operations without modifying the classes on
which it operates.
• It separates the operation from the object
collection and implements all of the appropriate
specializations of the required operation.

• This leads easy code maintainability and


avoids the use of the instance-of operator.
Visitor Pattern Class Diagram

operation

object collection
Components of the Visitor Pattern
Visitor
Concrete Visitor
Element (Visitable)
Concrete Element (Concrete Visitable)

Object Structure

Client
Visitor
• This is the interface or abstract class, which
declares the common interface for all types of
visitors.
• The visitor declares a bunch of visiting methods that
accept various concrete components as parameters.
This will be somewhat similar to the overloading
mechanism but the types of parameters should be
different hence the operations are totally different.
 Visit operations will be performed on each concrete
element in the object structure via the visit()
method. The input concrete element type will decide
the method to be called.
Concrete Visitor
• These are the concrete classes, which implement
all the operations described in the common visitor
interface.
• This each concrete visitor represents a
single behaviour of the object structure that is
each visitor is identical with different operations.
• Each concrete visitor will have a natively behaving
visit() method implementation.
Element (Visitable)
• This is an abstract component to represent the accept
operation of the visitor. It contains the accept() method
and should accept visitor objects as arguments. This is
considered as the entry point for the component
object to be ‘visited’ by the visitor object.
Concrete Element (Concrete Visitable)
• Concrete elements contain the actual
implementation of the abstract acceptance method
from the ‘Element’ component. Accept method will
take a visitor object as an argument in order to redirect
the call to a proper visitor’s method corresponding to
the current component class.
Object Structure
• The object structure is a class containing all the
element objects, which offers a mechanism to
iterate through all the elements.
• This object structure can be a collection or a
complex structure like a composite object.
Client
• The client does not know the concrete class
structure of the component and just call the
accept() method.
Example for Visitor Pattern
• Let’s assume a credit card scenario in a bank.
• The bank issues three types of credit cards for the
customers.
• Those cards get different types of offers
depending on the type of card.
• Card types are Silver, Gold and Platinum credit
cards and the offer types are Dining,
Supermarket, Hotel, and Travel.
• Bank system has to implement a system to
incorporate those offer types to appropriate credit
card types. Visitor design pattern suits best
to solve this design scenario in following way.
• Design pattern related class breakdown for the
credit card and offer types scenario,
• Credit Card Visitor: This is the base interface,
which acts as the ‘Visitor’ abstract component in the
design pattern.
• Offer: This is the base ‘Element’ interface for the
offer types object structure in the bank
• Following are the concrete visitor classes to
implement the abilities of each credit card type.
• Silver Credit Card Visitor / Gold Credit Card
Visitor                       
• Platinum Credit Card Visitor / Dinning Offer
Following are the concrete offer type classes to
differentiate each offer validities.
Dining Offer/ Super market Offer / Hotel Offer / 
Travel Offer     
• ‘Offer’ interface allows the ‘Credit Card Visitor’
interface to pass the right object so the correct
operation occurs on the right type of object. The
accept() method in ‘Offer’ interface pass the same
abstract visitor object and later specialized version
of visit() method is called. Method overloading is
used at this position to select the appropriate visit()
method.
Class Diagram for the Credit Card Offers
System
Code samples for credit card offers scenario
When to use the Visitor Design Pattern
• When there is a complex object structure with
many classes and different interface and client
needs to perform several operations on these objects
depending on their concrete classes.
• When the operations are distinct and
unrelated with one another it’s easy to keep
organized the classes and operations using this
pattern.
• When the classes in the object structure rarely
change but there is a need to define new operations
over the structure.
• When there is a need for adding a new
operation to the visitor hierarchy or new
component to the object structure we can achieve it
by not polluting the existing design
Visitor Pattern Limitations
• It’s necessary to know the return type of visit()
methods at the time of designing the pattern otherwise
we have to change the interface and all of its
implementations.
• It contains many implementations for the visitor
interface, which makes it harder to extend.
• If one new element object is added to the system,
we have to change all the implemented visitor
classes.
Thank You..

You might also like