12 GoF Patterns Behavioral
12 GoF Patterns Behavioral
Behavioral
Behavioral Patterns
Behavioral Patterns
Characterize ways in which classes or objects
interact and distribute responsibility
Problem
• There is a potentially variable number of "handler" objects
and a stream of requests that must be handled.
Need to efficiently process the requests without hard-
wiring handler relationships and precedence, or request-
to-handler mappings
Illustration: Problem
In a context-sensitive help facility for a graphical user
interface. For example : If button on the dialog widget is
selected as Part of the Interface - help specific to dialog will
be displayed
Note : If specific information on a widget is not present then
help system should display more general help.
Hence it’s natural to organize help information according to
its generality-from the most specific to the most general.
The problem here is that the object that ultimately provides
the help isn’t known explicitly to the object (e.g., the button)
that initiates the help request. What we need is a way to
decouple the button that initiates the help request from the
objects that might provide help information.
The idea of this pattern is to decouple senders and receivers by
giving multiple objects a chance to handle a request. The request
gets passed along a chain of objects until one of them handles it.
Illustration: solution
The first object in the chain receives the request
and either handles it or forwards it to the next
candidate on the chain, which does likewise. The
object that made the request has no explicit
knowledge of who will handle it - we say the
request has an implicit receiver.
Solution
Chain of Responsibility deals with traversing an object
tree from a node towards the root, in need to fulfill certain
responsibility. If none of the objects in the chain provide the
solution then the root will give a default solution.
Applicability
Use Chain of Responsibility when
◦ More than one object may handle a request, and the
handler isn’t known a priori, The handler should be
ascertained automatically
◦ You want to issue a request to one of several objects
without specifying the receiver explicitly
◦ The set of objects that can handle a request should be
specified dynamically.
Structure
Collaborations
When a client issues a request, the request propagates
along the chain until a ConcreteHandler object takes
responsibility for handling it.
Consequences
Chain of Responsibilities has the following benefits and liabilities:
• Reduced coupling
• Added flexibility in assigning responsibilities to objects
Also Known As
Action, Transaction
Problem:
Need to issue requests to objects without knowing anything about the
operation being requested or the receiver of the request.
Illustration: - Menus implemented using
command
Each choice in a Menu is an instance of a MenuItem
class. An Application class creates these menus and
their menu items along with the rest of the user interface.
The Application class also keeps track of Document objects
that a user has opened.
The application configures each MenuItem with an
instance of a concrete Command subclass. When the user
selects a Menuitem, the Menuitem calls Execute
on its command, and Execute carries out the operation.
Illustration: - menus implemented using command
MenuItems don’t know which subclass of Command they
use. Command subclasses store the receiver of
the request and invoke one or more operations on the
receiver. <<Example next slide>>
For example, PasteCommand supports pasting text from
the clipboard into a Document. PasteCommand’s receiver is
the Document object it is supplied upon instantiation. The
Execute operation invokes Paste on the receiving Document.
Illustration: - menus implemented using
OpenCommand’s Execute operation is
different: it prompts the user for a
document name, creates a
corresponding Document object,
adds the document to the receiving
application, and opens the document.
All of this is possible because the object that issues a request only needs
to know how to issue it; it doesn’t need to know how the request will be
carried out.
Solution
Command decouples the object that invokes the
operation from the one that knows how to perform it.
To achieve this separation, the designer creates an
abstract base class that maps a receiver (an object)
with an action (a pointer to a member function). The
base class contains an execute() method that simply
calls the action on the receiver.
All clients of Command objects treat each object as a
"black box" by simply invoking the object's virtual
execute() method whenever the client requires the
object's "service".
Sequences of Command objects can be assembled
into composite (or macro) commands.
Applicability
Use the Command pattern when you want to
● Parameterize objects by an action to perform, as
MenuItem.
You can express such parameterization in a procedural
language with a callback function, that is, a function that’s
registered somewhere to be called at a later point.
Commands are an object Oriented replacement for
callbacks.
● Specify, queue, and execute requests at different times. A
Command object can have a lifetime independent of the
original request. If the receiver of a request can be
represented in an address space-independent way, then
you can transfer a command object for the request to a
different process and fulfill the request there.
Applicability……….
Use the Command pattern when you want
to
● Support Undo
● Support logging changes so that they can be reapplied
in case of a system crash. Recovering form a crash
involves reloading logged commands form disk and re-
executing them with the execute operation.
● Structure a system around high-level operations built on
primitives operations. Such structure is common in
information system that support transactions.
Structure
Collaborations
● The client creates a ConcreteCommand object and
specifies its receiver.
● An Invoker object stores the ConcreteCommand
object.
● The invoker issues a request by calling Execute on
the command. When commands are undo-able,
ConcreteCommand stores state for undoing the com-
mand prior to invoking Execute.
● The ConcreteCommand object invokes operations
on its receiver to carry out the request.
Collaborations
On early television sets, a dial was used to change channels. When channel
surfing, the viewer was required to move the dial through each channel
position, regardless of whether or not that channel had reception. On
modern television sets, a next and previous button are used. When the
viewer selects the "next" button, the next tuned channel will be displayed.
Consider watching television in a hotel room in a strange city. When surfing
through channels, the channel number is not important, but the
programming is. If the programming on one channel is not of interest, the
viewer can request the next channel, without knowing its number.
Intent:
Provide a way to access the elements of
an aggregate object sequentially without
exposing its underlying representation
PROBLEM:
Need to "abstract" the traversal of wildly different data
structures so that algorithms can be defined that are capable of
interfacing with each transparently.
Illustration
For example: a List class would call for a ListIterator with
the following relation-ship between them:
<<create>>
<<create>>
Discussion
The Iterator abstraction is fundamental to an emerging
technology called "generic programming". This strategy
seeks to explicitly separate the notion of "algorithm"
from that of "data structure". The motivation is to:
promote component-based development, boost
productivity, and reduce configuration management.
As an example, if you wanted to support four data
structures (array, binary tree, linked list, and hash
table) and three algorithms (sort, find, and merge), a
traditional approach would require four times three
permutations to develop and maintain. Whereas, a
generic programming approach would only require four
plus three configuration items
Applicability
Use the Iterator pattern
Collaborations:
• A ConcreteIterator keeps track of the current object
in the aggregate and can compute the succeeding
object in the traversal.
Consequences
The Iterator pattern has three important consequences:
It supports variations in the traversal of an aggregate. Complex
aggregates may be traversed in many ways. For example, code
generation and semantic checking involve traversing parse trees.
Code generation may traverse the parse tree inorder or preorder.
Iterators make it easy to change the traversal
Iterafors simplify the Aggregate interface. Iterator’s traversal
interface obviates the need for a similar interface in Aggregate,
thereby simplifying the aggregate’s interface.
More than one traversal can be pending on an aggregate: An
Iterator keeps track of its own traversal state. Therefore you can
have more than one traversal in progress at once.
Model
Mediator
MEDIATOR
ATC Tower Example
of Mediator
The Mediator defines an object that controls how a set of objects interact.
Loose coupling between colleague objects is achieved by having colleagues
communicate with the Mediator, rather than with each other.
The control tower at a controlled airport demonstrates this pattern very well.
The pilots of the planes approaching or departing the terminal area
communicate with the tower, rather than explicitly communicating with one
another. The constraints on who can take off or land are enforced by the
tower. It is important to note that the tower does not control the whole flight. It
exists only to enforce constraints in the terminal area.
Intent
Define an object that encapsulates how a
Problem
• We want to design reusable components, but dependencies between
the potentially reusable pieces demonstrates the "spaghetti code"
phenomenon (trying to scoop a single serving results in an "all or
nothing clump").
Illustration: Problem
Consider the implementation of dialog
boxes in a GUI.
A dialog box uses a window to present a
collection of widgets such as buttons,
menus, and entry fields, as shown here.
The following interaction diagram illustrates how the objects cooperate to handle
a change in a list box’s selection.
media
tor
In the above model notice who the director communicates with list box and entry
field. Widgets communicate with each other only indirectly, through the director. All
they know is the director and they in turn don’t know each other.
Furthermore, because the behavior is localized in one class, it can be changed or
replaced by extending or replacing that class.
Applicability
Use the Mediator pattern when:
The Memento captures and externalizes an object's internal state, so the object
can be restored to that state later.
This pattern is common among do-it-yourself mechanics repairing drum brakes on
their cars. The drums are removed from both sides, exposing both the right and
left brakes. Only one side is disassembled, and the other side serves as a
Memento of how the brake parts fit together. Only after the job has been
completed on one side is the other side disassembled. When the second side is
disassembled, the first side acts as the Memento.
Intent
Without violating encapsulation, capture and
externalize an object's internal state so that the
object can be returned to this state later.
Also Known As
Token
Problem:
Need to restore an object back to its previous state (e.g. "undo" or "rollback"
operations). But object normally encapsulate some or all of their states,
making it inaccessible to other objects and impossible to save externally.
Exposing this state would violate encapsulation, which can compromise the
application’s reliability and extensibility.
Illustration: Graphical Editor
A caretaker request a memento form a originator, holds it for a time, and passes
it back to the originator, as the following interaction diagram illustrates.
Memento are passive. Only the originator that created a memento will assign or
retrieve its state.
Consequences:
1> preserving encapsulating boundary
2> It simplifies originator
3> using mementos might be expensive
4> Defining narrow and wide interfaces
5>Hidden costs in caring for mementos
Model
void MoveCommand::Execute () {
ConstraintSolver* solver = ConstraintSolver::Instance();
_state = solver->CreateMemento(); // create a memento
_target->Move(_delta);
solver->Solve();
}
void MoveCommand::Unexecute () {
ConstraintSolver* solver = ConstraintSolver::Instance();
_target->Move(-_delta);
solver->SetMemento(_state);
$ // restore solver state
solver->Solve();
}
<<attribute>>
Observer
OBSERVER
The Observer defines a one to many relationship, so that when one object changes
state, the others are notified and updated automatically.
Some auctions demonstrate this pattern. Each bidder possesses a numbered
paddle that is used to indicate a bid. The auctioneer starts the bidding, and
"observes" when a paddle is raised to accept the bid. The acceptance of the bid
changes the bid price, which is broadcast to all of the bidders in the form of a new
bid
Intent
Define a one-to-many dependency between
objects so that when one object changes state, all
its dependents are notified and updated
automatically.
Alternative Name:
Dependents, Publish-Subscribe
Problem:
How to handle a common side-effect (i.e. need to maintain consistency
between related object)of partitioning a system into a collection of
cooperating classes with out making the classes tightly coupled , -
which in turn makes classes less reusable.
Illustration
Subject
Solution:
The observer pattern describes how to
establish these relationships.
The key objects in this pattern are subject
and observer.
◦ A subject may have any number of dependent
observer.
◦ All observers are notified whenever the subject
undergoes a change in state.
}
Collaborations
• ConcreteSubject notifies its observers
whenever a change occurs that could make
its observers’ state inconsistent with its own.
NOTE: How observer object that initiates the change request postpones its
update until it gets a notification form the subject.
Consequences
Abstract coupling between Subject and
Observer
Support for broadcast communication.
Unexpected updates.
Model
Related patterns
Mediator: By encapsulating complex update
semantics, the ChangeManager acts as
mediator between subjects and observers.
The State pattern allows an object to change its behavior when its internal state
changes.
This pattern can be observed in a vending machine. Vending machines have
states based on the inventory, amount of currency deposited, the ability to make
change, the item selected, etc. When currency is deposited and a selection is
made, a vending machine will either deliver a product and no change, deliver a
product and change, deliver no product due to insufficient currency on deposit, or
deliver no product due to inventory depletion
Intent
Allow an object to alter its behavior when
its internal state changes. The object will
appear to change its class
Also Known As
• Objects for States
Problem:
A object can be in one of several different states, i.e.
its behavior is a function of its state
Non virtual
Singleton
//Default behavior:
/* virtual */
void TCPState::Transmit (TCPConnection*, TCPOctetStream*) { }
void TCPState::ActiveOpen (TCPConnection*) { }
void TCPState::PassiveOpen (TCPConnection*) { }
void TCPState::Close (TCPConnection*) { }
void TCPState::Synchronize (TCPConnection*) { }
/*
non - virtual */
void TCPEstablished::Transmit (
TCPConnection* t, TCPOctetStream* o
) {
t->ProcessOctet(o);
Strategy
STRATEGY
Also Known As
policy
Strategy
Make algorithms interchangeable---”changing the guts”
Alternative to subclassing
Choice of implementation at run-time
Increases run-time complexity
Context Strategy
ContextInterface() Operation()
ConcreteStrategy1 ConcreteStrategy2
Operation() Operation()
Strategy - Example
Example: drawing different connector styles
shape=router.recalculate(start,end);
redraw(shape);
Connector ConnectorRouter
route() Shape recalculate(Pt, Pt)
Many algorithms exits for performing a particular task [e.g – breaking a stream
of text into lines]. Hard-wiring all such algorithms into the classes that require
them isn’t desirable for several reasons
Illustration
Clients that need these algorithm ( line breaking ) get more
complex if they include algorithm’s code ( line-breaking code).
That makes client bigger and harder to maintain, especially if
they support multiple algorithms( line breaking algorithms).
◦ Its difficult to add new algorithms and vary existing ones when
a particular algorithm ( line breaking) is an integral part of
client.
Illustration: solution
The above explained problem can be avoided by defining
classes that encapsulate different algorithm(line breaking
algorithms).
An algorithm that’s encapsulated in this way is called a
strategy.
Note: separate
algorithm is encapsulated
in individual objects that
conform to common
interface
Solution
Replace the many, monolithic, conditional constructs with a Strategy
inheritance hierarchy and dynamic binding.
•Identify the protocol that provides the appropriate level of abstraction,
control, and interchangeability for the client.
•Specify this protocol in an abstract base class.
•Move all related conditional code into their own concrete derived
classes.
•Configure the original application with an instance of the Strategy
hierarchy, and delegate to that "contained" object whenever the
"algorithm" is required.
Related Patterns :
flyweight: Strategy objects often make good flyweights.
Template
Model
Basic Floor Plan Example of
Template Method
The Template Method defines a
skeleton of an algorithm in an
operation, and defers some
steps to subclasses.
Home builders use the Template Method when developing a new subdivision.
A typical subdivision consists of a limited number of floor plans, with different
variations available for each floor plan. Within a floor plan, the foundation,
framing, plumbing, and wiring will be identical for each house. Variation is
introduced in the latter stages of construction to produce a wider variety of
models.
Behavioral
Template Method
Intent
Problem:
Given a template method if we need to customize
or redefine a particular set in the algorithm one
may have to override the template function this
causes duplication and an inefficient usage of
template methods.
*
<<Create>>
DoCreateDocument()
Behavioral
Illustration
*
DoCreateDocument()
Behavioral : Template Method
Solution
A template method pattern gives a solution.
Structure
TemplateMethod(){
}
Behavioral
Applicability
To implement the invariant parts of an algorithm
once and leave it up to subclasses to implement
the behavior that can vary.
Collaborations
• ConcreteClass relies on abstractClass to
implement the invariant steps of the algorithm.
Behavioral
Consequences
1. Concrete operations
2. Concrete AbstractClass operations
3. Primitive operations
4. Factory methods
5. Hook operations, which provide default
behavior that subclasses can extend if
necessary. A hook operation often does
nothing by default.
Model
Behavioral
Related Patterns
Factory Methods are often called by template
methods. In the Motivation example, the
factory method DoCreateDocument is called
by the template method OpenDocument.
The classes defining the object structure rarely change, but you
often want to define new operations over the structure.
Changing the object structure classes requires redefining the
interface t o all visitors, which is potentially costly. If the object
structure classes change often, then its probably better to
define the operation in those classes.
Structure
"The Visitor becomes more useful when there are several classes with
different interfaces and we want to encapsulate how we get data from these
classes."
Collaborations
A client that uses the Visitor pattern must create a
ConcreteVisitor object and then traverse the object
structure, visiting each element with the visitor.
When an element is visited, it calls the visitor operation
that corresponds to visitor access its state, if necessary.
Consequences
1 Visitor makes adding new operations easy:
Add functions to class libraries for which you either do not
have the source or cannot change the source
2. A visitor gathers related operations and separates
unrelated ones:Gather related operations into a single
class rather than force you to change or derive classes to
add these operations
3. Adding new ConcreteElement classes is hard.
4. Visiting across class hierarchies: