Behavioral Patterns
Behavioral Patterns
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
3. Concrete Mediators
encapsulate relations between
various components.
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.