You are on page 1of 81

Behavioural Design Pattern

CHAIN COMMAND
RESPONSIBILITY
ITERATOR MEDIATOR
MOMENTO OBSERVER
STATE STRATEGY
TEMPLATE VISITOR
METHOD
Chain Responsibility

DEFINITION

Chain of Responsibility is a
behavioral design pattern that lets
you pass requests along a chain of
handlers. Upon receiving a request,
each handler decides either to
process the request or to pass it to
the next handler in the chain.
Chain Responsibility EXAMPLE
You have an online shop where you only receive order from an authenticated users.
To authenticate the order there is several step that you have to do, such as and
authentication of a user to the system whenever it receives a request that contains
the user’s credentials, an order validation step to sanitize the data in a request, a
check that filters repeated failed requests coming from the same IP address and
another check which lets the request pass through to the system only if there’s no
suitable cached response.

The code of the checks, which had already looked like a mess, became more and
more bloated as you added each new feature. Changing one check sometimes
affected the others. Worst of all, when you tried to reuse the checks to protect other
components of the system, you had to duplicate some of the code since those
components required some of the checks, but not all of them.
Chain Responsibility EXAMPLE

The Chain of Responsibility relies on transforming particular behaviors into stand-alone objects called
handlers. In our case, each check should be extracted to its own class with a single method that performs
the check. The request, along with its data,
is passed to this method as an argument.

The pattern suggests that you link these handlers into a chain. Each linked handler has a field for storing a
reference to the next handler in the chain. In addition to processing a request, handlers pass the request
further along the chain. The request travels along the chain until all handlers have had a chance to
process it. A handler can decide not to pass the request further down the chain and effectively stop any
further processing.

However, there’s a slightly different approach (and it’s a bit more canonical) in which, upon receiving a
request, a handler decides whether it can process it. If it can, it doesn’t pass the request any further. So it’s
either only one handler that processes the request or none at all. This approach is very common when
dealing with events in stacks of elements within a graphical user interface.
Chain Responsibility APPLICABILITY

Use the Chain of Responsibility pattern when your program is expected to process
different kinds of requests in various ways, but the exact types of requests and
their sequences are unknown beforehand.
Use the pattern when it’s essential to execute several handlers in a particular order.
Use the CoR pattern when the set of handlers and their order are supposed to
change at runtime.
Chain Responsibility HOW TO IMPLEMENT
Declare the handler interface and describe the signature of a method for handling requests.
To eliminate duplicate boilerplate code in concrete handlers, it might be worth creating an abstract
base handler class, derived from the handler interface.
One by one create concrete handler subclasses and implement their handling methods. Each handler
should make two decisions when receiving a request:
Whether it’ll process the request.
Whether it’ll pass the request along the chain.
The client may either assemble chains on its own or receive pre-built chains from other objects. In the
latter case, you must implement some factory classes to build chains according to the configuration or
environment settings.
The client may trigger any handler in the chain, not just the first one. The request will be passed along
the chain until some handler refuses to pass it further or until it reaches the end of the chain.
Due to the dynamic nature of the chain, the client should be ready to handle the following scenarios:
The chain may consist of a single link.
Some requests may not reach the end of the chain.
Others may reach the end of the chain unhandled.
Command
DEFINITION

Command is a behavioral design


pattern that turns a request into a
stand-alone object that contains all
information about the request. This
transformation lets you parameterize
methods with different requests,
delay or queue a request’s execution,
and support undoable operations.
Command EXAMPLE

After a long walk through the city, you get to a nice restaurant and sit at the table by
the window. A friendly waiter approaches you and quickly takes your order, writing it
down on a piece of paper. The waiter goes to the kitchen and sticks the order on the
wall. After a while, the order gets to the chef, who reads it and cooks the meal
accordingly. The cook places the meal on a tray along with the order. The waiter
discovers the tray, checks the order to make sure everything is as you wanted it, and
brings everything to your table.

The paper order serves as a command. It remains in a queue until the chef is ready
to serve it. The order contains all the relevant information required to cook the meal.
It allows the chef to start cooking right away instead of running around clarifying the
order details from you directly.
Command APPLICABILITY

Use the Command pattern when you want to parametrize objects with operations.
Use the Command pattern when you want to queue operations, schedule their
execution, or execute them remotely.
Use the Command pattern when you want to implement reversible operations.
Command HOW TO IMPLEMENT
1. Declare the command interface with a single execution method.
2. Start extracting requests into concrete command classes that implement the command
interface. Each class must have a set of fields for storing the request arguments along with a
reference to the actual receiver object. All these values must be initialized via the command’s
constructor.
3. Identify classes that will act as senders. Add the fields for storing commands into these classes.
Senders should communicate with their commands only via the command interface. Senders
usually don’t create command objects on their own, but rather get them from the client code.
4. Change the senders so they execute the command instead of sending a request to the receiver
directly.
5. The client should initialize objects in the following order:
a. Create receivers.
b. Create commands, and associate them with receivers if needed.
c. Create senders, and associate them with specific commands.
Iterator

DEFINITION

Iterator is a behavioral design


pattern that lets you traverse
elements of a collection without
exposing its underlying
representation (list, stack, tree, etc.).
Iterator EXAMPLE

The main idea of the Iterator pattern is to extract the traversal behavior of a collection into a separate
object called an iterator.

In addition to implementing the algorithm itself, an iterator object encapsulates all of the traversal details,
such as the current position and how many elements are left till the end. Because of this, several iterators
can go through the same collection at the same time, independently of each other.

Usually, iterators provide one primary method for fetching elements of the collection. The client can keep
running this method until it doesn’t return anything, which means that the iterator has traversed all of the
elements.

All iterators must implement the same interface. This makes the client code compatible with any collection
type or any traversal algorithm as long as there’s a proper iterator. If you need a special way to traverse a
collection, you just create a new iterator class, without having to change the collection or the client.
Iterator APPLICABILITY

Use the Iterator pattern when your collection has a complex data structure under
the hood, but you want to hide its complexity from clients (either for convenience
or security reasons).
Use the pattern to reduce duplication of the traversal code across your app.
Use the Iterator when you want your code to be able to traverse different data
structures or when types of these structures are unknown beforehand.
Iterator HOW TO IMPLEMENT

1. Declare the iterator interface. At the very least, it must have a method for fetching the next element
from a collection. But for the sake of convenience you can add a couple of other methods, such as
fetching the previous element, tracking the current position, and checking the end of the iteration.
2. Declare the collection interface and describe a method for fetching iterators. The return type should be
equal to that of the iterator interface. You may declare similar methods if you plan to have several
distinct groups of iterators.
3. Implement concrete iterator classes for the collections that you want to be traversable with iterators. An
iterator object must be linked with a single collection instance. Usually, this link is established via the
iterator’s constructor.
4. Implement the collection interface in your collection classes. The main idea is to provide the client with
a shortcut for creating iterators, tailored for a particular collection class. The collection object must pass
itself to the iterator’s constructor to establish a link between them.
5. Go over the client code to replace all of the collection traversal code with the use of iterators. The client
fetches a new iterator object each time it needs to iterate over the collection elements.
Mediator
DEFINITION

Mediator is a behavioral design


pattern that lets you reduce chaotic
dependencies between objects. The
pattern restricts direct
communications between the
objects and forces them to
collaborate only via a mediator
object.
Mediator EXAMPLE

The Mediator pattern suggests that you should cease all direct communication
between the components which you want to make independent of each other.
Instead, these components must collaborate indirectly, by calling a special mediator
object that redirects the calls to appropriate components. As a result, the
components depend only on a single mediator class instead of being coupled to
dozens of their colleagues.

This way, the Mediator pattern lets you encapsulate a complex web of relations
between various objects inside a single mediator object. The fewer dependencies a
class has, the easier it becomes to modify, extend or reuse that class.
Mediator APPLICABILITY

Use the Mediator pattern when it’s hard to change some of the classes because
they are tightly coupled to a bunch of other classes.
Use the pattern when you can’t reuse a component in a different program
because it’s too dependent on other components.
Use the Mediator when you find yourself creating tons of component subclasses
just to reuse some basic behavior in various contexts.
Mediator HOW TO IMPLEMENT
1. Identify a group of tightly coupled classes which would benefit from being more independent (e.g., for
easier maintenance or simpler reuse of these classes).
2. Declare the mediator interface and describe the desired communication protocol between mediators
and various components. In most cases, a single method for receiving notifications from components is
sufficient.
3. Implement the concrete mediator class. This class would benefit from storing references to all of the
components it manages.
4. You can go even further and make the mediator responsible for the creation and destruction of
component objects. After this, the mediator may resemble a factory or a facade.
5. Components should store a reference to the mediator object. The connection is usually established in
the component’s constructor, where a
6. mediator object is passed as an argument.
7. Change the components’ code so that they call the mediator’s notification method instead of methods
on other components. Extract the code that involves calling other components into the mediator class.
8. Execute this code whenever the mediator receives notifications from that component.
Momento

DEFINITION

Memento is a behavioral design


pattern that lets you save and
restore the previous state of an
object without revealing the
details of its implementation.
Momento EXAMPLE
Imagine that you’re creating a text editor app. In addition to simple text editing, your
editor can format text, insert inline images, etc.

At some point, you decided to let users undo any operations carried out on the text.
This feature has become so common over the years that nowadays people expect
every app to have it. For the implementation, you chose to take the direct approach.
Before performing any operation, the app records the state of all objects and saves it
in some storage. Later, when a user decides to revert an action, the app fetches the
latest snapshot from the history and uses it to restore the state of all objects.
Momento EXAMPLE

The Memento pattern delegates creating the state snapshots to the actual owner of
that state, the originator object. Hence, instead of other objects trying to copy the
editor’s state from the “outside,” the editor class itself can make the snapshot
since it has full access to its own state.

The pattern suggests storing the copy of the object’s state in a special object called
memento. The contents of the memento aren’t accessible to any other object except
the one that produced it. Other objects must communicate with mementos using a
limited interface which may allow fetching the snapshot’s metadata (creation time,
the name of the performed operation,  etc.), but not the original object’s state
contained in the snapshot.
Implementation based on nested classes
Implementation based on an intermediate interface
Implementation with even stricter encapsulation
Momento APPLICABILITY

Use the Memento pattern when you want to produce snapshots of the object’s
state to be able to restore a previous state of the object.
Use the pattern when direct access to the object’s fields/getters/setters violates
its encapsulation.
Momento HOW TO IMPLEMENT
1. Determine what class will play the role of the originator. It’s important to know
whether the program uses one central object of this type or multiple smaller ones.
2. Create the memento class. One by one, declare a set of fields that mirror the fields
declared inside the originator class.
3. Make the memento class immutable. A memento should accept the data just
once, via the constructor. The class should have no setters.
4. If your programming language supports nested classes, nest the memento inside
the originator. If not, extract a blank interface from the memento class and make
all other objects use it to refer to the memento. You may add some metadata
operations to the interface, but nothing that exposes the originator’s state.
5. Add a method for producing mementos to the originator class. The originator
should pass its state to the memento via one or multiple arguments of the
memento’s constructor.
Momento HOW TO IMPLEMENT
1. Add a method for restoring the originator’s state to its class. It should accept a
memento object as an argument. If you extracted an interface in the previous
step, make it the type of the parameter. In this case, you need to typecast the
incoming object to the mediator class, since the originator needs full access to
that object.
2. The caretaker, whether it represents a command object, a history, or something
entirely different, should know when to request new mementos from the originator,
how to store them and when to restore the originator with a particular memento.
3. The link between caretakers and originators may be moved into the memento
class. In this case, each memento must be connected to the originator that had
created it. The restoration method would also move to the memento class.
However, this would all make sense only if the memento class is nested into
originator or the originator class provides sufficient setters for overriding its state.
Observer

DEFINITION

Observer is 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.
Observer EXAMPLE

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. Fear not! Everything isn’t as complicated as it
sounds. In reality, this mechanism consists of 1) an array field for storing a list of
references to subscriber objects and 2) several public methods which allow adding
subscribers to and removing them from that list.
Observer APPLICABILITY

Use the Observer pattern when changes to the state of one object may require
changing other objects, and the actual set of objects is unknown beforehand or
changes dynamically.
Use the pattern when some objects in your app must observe others, but only for a
limited time or in specific cases.
Observer HOW TO IMPLEMENT
Look over your business logic and try to break it down into two parts: the core
functionality, independent from other code, will act as the publisher; the rest will
turn into a set of subscriber classes.
Declare the subscriber interface. At a bare minimum, it should declare a single
update method.
Declare the publisher interface and describe a pair of methods for adding a
subscriber object to and removing it from the list. Remember that publishers must
work with subscribers only via the subscriber interface.
Decide where to put the actual subscription list and the implementation of
subscription methods. Usually, this code looks the same for all types of publishers,
so the obvious place to put it is in an abstract class derived directly from the
publisher interface. Concrete publishers extend that class, inheriting the
subscription behavior.
Observer HOW TO IMPLEMENT

Create concrete publisher classes. Each time something important happens inside
a publisher, it must notify all its subscribers.
Implement the update notification methods in concrete subscriber classes. Most
subscribers would need some context data about the event. It can be passed as
an argument of the notification method.
The client must create all necessary subscribers and register them with proper
publishers.
State

DEFINITION

State is a behavioral design pattern


that lets an object alter its behavior
when its internal state changes. It
appears as if the object changed its
class.
State EXAMPLE
The State pattern suggests that you create new classes for all possible states of an object and
extract all state-specific behaviors into these classes.

Instead of implementing all behaviors on its own, the original object, called context, stores a
reference to one of the state objects that represents its current state, and delegates all the state-
related work to that object.

To transition the context into another state, replace the active state object with another object that
represents that new state. This is possible only if all state classes follow the same interface and
the context itself works with these objects through that interface.

This structure may look similar to the Strategy pattern, but there’s one key difference. In the State
pattern, the particular states may be aware of each other and initiate transitions from one state to
another, whereas strategies almost never know about
each other.
State APPLICABILITY

Use the State pattern when you have an object that behaves differently depending
on its current state, the number of states is enormous, and the state-specific code
changes frequently.
Use the pattern when you have a class polluted with massive conditionals that
alter how the class behaves according to the current values of the class’s fields.
Use State when you have a lot of duplicate code across similar states and
transitions of a condition-based state machine.
State HOW TO IMPLEMENT
1. Decide what class will act as the context. It could be an existing class which already has the
state-dependent code; or a new class, if the state-specific code is distributed across multiple
classes.
2. Declare the state interface. Although it may mirror all the methods declared in the context, aim
only for those that may contain state-specific behavior.
3. For every actual state, create a class that derives from the state interface. Then go over the
methods of the context and extract all code related to that state into your newly created class.
4. In the context class, add a reference field of the state interface type and a public setter that
allows overriding the value of that field.
5. Go over the method of the context again and replace empty state conditionals with calls to
corresponding methods of the state object.
6. To switch the state of the context, create an instance of one of the state classes and pass it to
the context. You can do this within the context itself, or in various states, or in the client.
Wherever this is done, the class becomes dependent on the concrete state class that it
instantiates.
Strategy

DEFINITION

Strategy is a behavioral design


pattern that lets you define a family
of algorithms, put each of them into
a separate class, and make their
objects interchangeable.
Strategy EXAMPLE

The Strategy pattern suggests that you take a class that does something specific in a lot of different ways
and extract all of these algorithms into separate classes called strategies.

The original class, called context, must have a field for storing a reference to one of the strategies. The
context delegates the work to a linked strategy object instead of executing it on its own.

The context isn’t responsible for selecting an appropriate algorithm for the job. Instead, the client passes
the desired strategy to the context. In fact, the context doesn’t know much about strategies. It works with all
strategies through the same generic interface, which only exposes a single method for triggering the
algorithm encapsulated within the selected strategy.

This way the context becomes independent of concrete strategies, so


you can add new algorithms or modify existing ones without changing the
code of the context or other strategies.
Strategy APPLICABILITY

Use the Strategy pattern when you want to use different variants of an algorithm
within an object and be able to switch from one algorithm to another during
runtime.
Use the Strategy when you have a lot of similar classes that only differ in the way
they execute some behavior.
Use the pattern to isolate the business logic of a class from the implementation
details of algorithms that may not be as important in the context of that logic.
Use the pattern when your class has a massive conditional operator that switches
between different variants of the same algorithm.
Strategy HOW TO IMPLEMENT

In the context class, identify an algorithm that’s prone to frequent changes. It may
also be a massive conditional that selects and executes a variant of the same
algorithm at runtime.
Declare the strategy interface common to all variants of the algorithm.
One by one, extract all algorithms into their own classes. They should all
implement the strategy interface.
In the context class, add a field for storing a reference to a strategy object. Provide
a setter for replacing values of that field.
The context should work with the strategy object only via the strategy interface.
The context may define an interface which lets the strategy access its data.
Clients of the context must associate it with a suitable strategy that matches the
way they expect the context to perform its primary job.
Template Method

DEFINITION

Template Method is a behavioral


design pattern that defines the
skeleton of an algorithm in the
superclass but lets subclasses
override specific steps of the
algorithm without changing its
1. structure.
Template Method EXAMPLE

The Template Method pattern suggests that you break down an algorithm into a series of steps,
turn these steps into methods, and put a series of calls to these methods inside a single “template
method.” The steps may either be abstract, or have some default implementation. To use the
algorithm, the client is supposed to provide its own subclass, implement all abstract steps, and
override some of the optional ones if needed (but not the template method itself).

There are two types of steps:


abstract steps must be implemented by every subclass
optional steps already have some default implementation, but still can be overridden if needed

There’s another type of step, called hooks. A hook is an optional step with an empty body. A
template method would work even if a hook isn’t overridden. Usually, hooks are placed before and
after crucial steps of algorithms, providing subclasses with additional extension points for an
algorithm.
Template Method APPLICABILITY

Use the Template Method pattern when you want to let clients extend only
particular steps of an algorithm, but not the whole algorithm or its structure.
Use the pattern when you have several classes that contain almost identical
algorithms with some minor differences. As a result, you might need to modify all
classes when the algorithm changes.
Template Method HOW TO IMPLEMENT

1. Analyze the target algorithm to see whether you can break it into steps. Consider
which steps are common to all subclasses and which ones will always be unique.
2. Create the abstract base class and declare the template method and a set of
abstract methods representing the algorithm’s steps. Outline the algorithm’s
structure in the template method by executing corresponding steps. Consider
making the template method final to prevent subclasses from overriding it.
3. It’s okay if all the steps end up being abstract. However, some steps might benefit
from having a default implementation. Subclasses don’t have to implement those
methods.
4. Think of adding hooks between the crucial steps of the algorithm.
5. For each variation of the algorithm, create a new concrete subclass. It must
implement all of the abstract steps, but may also override some of the optional
ones.
Visitor

DEFINITION

Visitor is a behavioral design pattern


that lets you separate algorithms
from the objects on which they
operate.
Visitor EXAMPLE

The Visitor pattern suggests that you place the new behavior into a separate class
called visitor, instead of trying to integrate it into existing classes. The original object
that had to perform the behavior is now passed to one of the visitor’s methods as an
argument, providing the method access to all necessary data contained within the
object.
Visitor APPLICABILITY

Use the Visitor when you need to perform an operation on all elements of a
complex object structure (for example, an object tree).
Use the Visitor to clean up the business logic of auxiliary behaviors.
Use the pattern when a behavior makes sense only in some classes of a class
hierarchy, but not in others.
Visitor HOW TO IMPLEMENT

1. Declare the visitor interface with a set of “visiting” methods, one per each concrete element
class that exists in the program.
2. Declare the element interface. If you’re working with an existing element class hierarchy, add the
abstract “acceptance” method to the base class of the hierarchy. This method should accept a
visitor object as an argument.
3. Implement the acceptance methods in all concrete element classes. These methods must
simply redirect the call to a visiting method on the incoming visitor object which matches the
class of the current element.
4. The element classes should only work with visitors via the visitor interface. Visitors, however,
must be aware of all concrete element classes, referenced as parameter types of the visiting
methods.
5. For each behavior that can’t be implemented inside the element hierarchy, create a new
concrete visitor class and implement all of the visiting methods.
6. The client must create visitor objects and pass them into elements via “acceptance” methods.
Implemented Design Pattern

Repository (a special kind of Visitor (Behavioral


Singgleton
Facade (structural) but also Design Pattern) -
(Creational Design
as a special kind of Factory User Management
Pattern)
(creational)
Proposed Design Pattern

Template Method (Behavioral Design Pattern)


Saving setup time at the
begining of sprint
Why
Programmer can focus on
interpret the business
Template
process into the
programming
Method?
Standarization in the
programming can facilitate (Behavioral Design Pattern)

other programmer to scale


out the app

You might also like