0% found this document useful (0 votes)
12 views

Behavioral Patterns

Uploaded by

David Raju
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Behavioral Patterns

Uploaded by

David Raju
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 34

BEHAVIORAL

PATTERNS
Yaksha Kasturi - 017
ITERATOR
● Iterator is a behavioral design pattern that lets you traverse
elements of a collection without exposing its underlying
representation (list, stack, tree, etc.).
● Need to "abstract" the traversal of wildly different data structures
so that algorithms can be defined that are capable of interfacing
with each transparently.
● The main idea is to extract the traversal behavior of a collection
into a separate object called an iterator.
Structure:
1. Iterator interface declares
operations

2. Concrete iterator
implements algorithm for
traversing

3. Collection interfaces
declares methods to get
iterators for collection

4. Concrete Collections return


new instances of a particular
concrete iterator class

5. The Client works with both


collections and iterators via
their interfaces.
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).
● To reduce duplication of the traversal code across your app.
● When you want your code to be able to traverse different data
structures or when types of these structures are unknown
beforehand
Relations with other patterns:
● Factory Method + Iterator = To let collection subclasses return
different types of iterators compatible with the collections.
● Memento + Iterator = To capture the current iteration state and
roll it back if necessary
● Visitor + Iterator = To traverse a complex data structure and
execute some operation over its elements
MEDIATOR
● Mediator lets you reduce chaotic dependencies between objects.
It restricts direct communications between the objects and forces
them to collaborate only via a mediator object.
● The primary goal of Mediator is to eliminate mutual dependencies
among a set of system components. Instead, these components
become dependent on a single mediator object.
● This pattern also promotes loose coupling by keeping objects from
referring to each other explicitly.
Structure:
1. Components are various classes
that contain some business logic

2. The Mediator interface


declares methods of
communication with
components.

3. Concrete Mediators
encapsulate relations between
various components.

Components must not be aware of


other components. If something
important happens within or to a
component, it must only notify the
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.
● When you can’t reuse a component in a different program
because it’s too dependent on other components.
● When you find yourself creating tons of component subclasses
just to reuse some basic behavior in various contexts.
Relations with other patterns:
● Chain of Responsibility + Command + Mediator + Observer =
To address various ways of connecting senders and receivers of
requests
● Facade & Mediator are similar - they try to organize collaboration
between lots of tightly coupled classes.
● Visitor + Iterator = To traverse a complex data structure and
execute some operation over its elements
MEMENTO
● 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.
● Need to restore an object back to its previous state (e.g. "undo" or
"rollback" operations).
● The pattern suggests storing the copy of the object’s state in a
special object called memento.
Structure:
1. The Originator class can produce snapshots of its own state, as
well as restore its state from

2. The Memento is a value object that acts as a snapshot of the


originator’s state.

3. The Caretaker knows not only “when” and “why” to capture the
originator’s state, but also when the state should be restored.

The memento class is nested inside the originator. This lets the
originator access the fields and methods of the memento. The
caretaker has very limited access.
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.
● When direct access to the object’s fields/getters/setters violates its
encapsulation.
Relations with other patterns:
● Command + Memento = To implement undo
● Memento + Iterator = To capture the current iteration state and
roll it back if necessary
● Sometimes Prototype can be a simpler alternative to Memento -
This works if the object, the state of which you want to store in the
history, is fairly straightforward and doesn’t have links to external
resources, or the links are easy to re-establish.
OBSERVER
● 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.
● A large monolithic design does not scale well as new graphing or
monitoring requirements are levied.
● It 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.
Structure:
1. The Publisher issues events
of interest to other objects.

2. The Subscriber interface


declares the notification
interface.
3. Concrete Subscribers
perform some actions in
response to notifications
issued by the publisher.

4. The Client creates publisher


and subscriber objects
separately and then registers
subscribers for publisher
updates.
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.
● When some objects in your app must observe others, but only for
a limited time or in specific cases.
Relations with other patterns:
● Chain of Responsibility + Command + Mediator + Observer =
To address various ways of connecting senders and receivers of
requests
● Mediator and Observer are similar. In most cases, you can
implement either of these patterns; but sometimes you can apply
both simultaneously.
STATE
● 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.
● A monolithic object's behavior is a function of its state, and it must
change its behavior at run-time depending on that state.
● It suggests that you create new classes for all possible states of an
object and extract all state-specific behaviors into these classes.
Structure:
1. Context stores a reference to
one of the concrete state
objects and delegates to it all
state-specific work.

2. The State interface declares


the state-specific methods.

3. Concrete States provide their


own implementations for the
state-specific methods.

State objects may store a


backreference to the context
object. Both context and concrete
states can set the next state of the
context.
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.
● 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.
● When you have a lot of duplicate code across similar states and
transitions of a condition-based state machine.
Relations with other patterns:
● Bridge, State, Strategy (and to some degree Adapter) have very
similar structures. Indeed, all of these patterns are based on
composition, which is delegating work to other objects. However,
they all solve different problems.
● State can be considered as an extension of Strategy. Both
patterns are based on composition: Strategy makes these objects
completely independent while State doesn’t restrict dependencies
between concrete states.
STRATEGY
● 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.
● It 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.
Structure:
1. The Context maintains a
reference to one of the concrete
strategies
2. The Strategy interface is
common to all concrete
strategies.
3. Concrete Strategies implement
different variations of an
algorithm the context uses.
4. The Client creates a specific
strategy object and passes it to
the context.

The context calls the execution


method on the linked strategy object
each time it needs to run the
algorithm.
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.
● You have a lot of similar classes that only differ in the way they
execute some behavior.
● You want 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.
● Your class has a massive conditional statement that switches
between different variants of the same algorithm.
Relations with other patterns:
● Bridge, State, Strategy (and to some degree Adapter) have very
similar structures.
● Command and Strategy may look similar because you can use
both to parameterize an object with some action but they have
very different intents.
● Decorator lets you change the skin of an object, while Strategy
lets you change the guts.
● Template Method works at the class level, so it’s static. Strategy
works on the object level, letting you switch behaviors at runtime.
● State can be considered as an extension of Strategy.
TEMPLATE
● Template Method defines the skeleton of an algorithm in the
superclass but lets subclasses override specific steps of the
algorithm without changing its structure.
● Two different components have significant similarities, but
demonstrate no reuse of common interface or implementation. If
a change common to both components becomes necessary,
duplicate effort must be expended.
Structure:
1. The Abstract Class declares
methods that act as steps of
an algorithm, as well as the
actual template method
which calls these methods in
a specific order. The steps
may either be declared
abstract or have some
default implementation.

2. Concrete Classes can


override all of the steps, but
not the template method
itself.
Applicability:
Use the Template pattern
● When you want to let clients extend only particular steps of an
algorithm, but not the whole algorithm or its structure.
● 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.
Relations with other patterns:
● Factory Method is a specialization of Template Method. At the
same time, a Factory Method may serve as a step in a large
Template Method.
● Template Method is based on inheritance: it lets you alter parts
of an algorithm by extending those parts in subclasses.
Strategy is based on composition: you can alter parts of the
object’s behavior by supplying it with different strategies that
correspond to that behavior.
VISITOR
● Visitor is a behavioral design pattern that lets you separate
algorithms from the objects on which they operate.
● It 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.
Structure:
1. The Visitor interface declares a set
of visiting methods that can take
concrete elements of an object
structure as arguments.

2. Each Concrete Visitor implements


several versions of the same
behaviors.

3. The Element interface declares a


method for “accepting” visitors.

4. Each Concrete Element must


implement the acceptance method.

5. The Client usually represents a


collection or some other complex
object.
Applicability:
Use the Visitor pattern
● When you need to perform an operation on all elements of a
complex object structure (for example, an object tree).
● To clean up the business logic of auxiliary behaviors.
● When a behavior makes sense only in some classes of a class
hierarchy, but not in others.
Relations with other patterns:
● Visitor can be treated as a powerful version of the Command
pattern. Its objects can execute operations over various objects of
different classes.
● Visitor can be used to execute an operation over an entire
Composite tree.
● Visitor can be used along with Iterator to traverse a complex
data structure and execute some operation over its elements,
even if they all have different classes.
THANK YOU

You might also like