Behavioral patterns are concerned with algorithms and communication between them. There are 11 patterns in this group.
- Chain of responsibility : A way of passing a request between a chain of objects.
- Command : Encapsulate a command request as an object
- Interpreter : A way to include language elements in a program.
- Iterator: Sequentially access the elements of a collection.
- Mediator : Defines simplified communication between classes.
- Memento :Capture and restore an objects internal state
- Observer : A way of notifying change to number of classes
- State: Alter an objects behavior when its state changes.
- Strategy: Encapsulates an algorithm inside a class.
10. Template: Defer the exact steps of an algorithm to a subclass.
11. Visitor: Defines a new operation to a class without change.
Strategy Pattern
The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it. The algorithms can also be expressed independently of the data they are using. With this a family of algorithms is defined and encapsulated. Then the strategy lets these algorithms vary independently from the client that uses it.
State Pattern
When the state inside an object changes, it can change its behavior by switching to a set of different operations. This is achieved by an object variable changing its subclass, within a hierarchy. It is a dynamic version of the strategy pattern where objects change behavior at run time.
Template Method
The Template Method pattern enables algorithms to defer certain steps to subclasses. The structure of the algorithm does not change, but small well-defined parts of its operation are handled elsewhere. i.e. the skeleton of the class is defined in an abstract class and then the subclasses can change the implementation of few methods.
Pattern Comparison
There are considerable similarities between the Strategy and State patterns, but the main difference is one of intent:
• A Strategy object encapsulates an algorithm
• A State object encapsulates a state-dependent behavior (and possibly state transitions)
Both patterns are concerned with polymorphism. Both patterns define a parent interface or abstract class and a series of subclasses that implement the methods therein. And both patterns have a context that they maintain and use to decide on state transitions. So, the biggest difference between the patterns is that we encapsulate an algorithm into strategy classes in the Strategy pattern, but we encapsulate state into state classes in the State pattern. The Template Method pattern is more like the Strategy pattern in that it is algorithm based. The steps of the algorithm are specified in the Template Method and some are
deferred to domain classes.
Chain of Responsibility pattern
The Chain of Responsibility pattern works with a list of Handler objects that have limitations on the nature of the requests they can deal with. If an object cannot handle a request, it passes it on to the next object in the chain. At the end of the chain, there can be either default or exceptional behavior.
So in this case we avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it.
Command Pattern
The Command pattern creates distance between the client that requests an operation and the object that can perform it. This pattern is particularly versatile. It can support:
• Sending requests to different receivers
• Queuing, logging, and rejecting requests
• Composing higher-level transactions from primitive operations
• Redo and Undo functionality
The same command can be activated by different means like menu, button or context menu.
The concept is like this. The invoker is responsible for keeping track of all the commands. Client registers the command with the invoker and binds the command to a control’s action. This binding can happen with multiple controls. So when the control’s action is initiated, the command is executed.
Pattern Comparison
A similarity between the Chain of Responsibility and the Command patterns is that they decouple senders and receivers, thus improving the layering and reusability of a system. The Chain of Responsibility pattern supports decoupling by passing a request between potential receivers, whereas the Command pattern supports using a command object to encapsulate a request.
Iterator Pattern
The Iterator pattern provides a way of accessing elements of a collection sequentially, without knowing how the collection is structured. As an extension, the pattern allows for filtering elements in a variety of ways as they are generated.
The Iterator pattern defines a fundamental separation between the iteration process and the enumeration process. Even in trivial cases the separation is advantageous, but its benefits are really felt when:
• The structure is complex.
• Different iterations are required over it, potentially at the same time.
• The same structure and iterations can be applied to different data.
The iterator pattern is used when:
• There are various ways of traversing it (several enumerators).
• There are different collections for the same kind of traversing.
• Different filters and orderings might apply.
In C# LINQ, Lamda expression and IEnumerable interface can be used to support this pattern
Mediator Pattern
The Mediator pattern is there to enable objects to communicate without knowing each other’s identities. It also encapsulates a protocol that objects can follow. This pattern defines a simplified communication between classes.
The mailing list and chat room are examples of this pattern. Mailing list members are people interested in a specific topic.
People interested in the topic can join the mailing list by subscribing to it using a special message subject (“Subscribe”). Any messages that come in will go to all of the list’s subscribers. Members can remove themselves from the list at any time by sending an “Unsubscribe” message. The mediator i.e. the mailing list acts as a moderator also for applying any specific moderation to the topic.
This pattern makes use of the events and delegates.
Mediator pattern is used when
• Objects communicate in well-structured but potentially complex ways.
• The objects’ identities should be protected even though they communicate.
• Some object behaviors can be grouped and customized.
The Mediator pattern can have a performance impact on a system. Because all communication must go through the mediator, it can become a bottleneck. But it simplifies the communication. If objects ommunicate directly with each other, it becomes difficult to move or reuse any one of them. Mediators can be set up to collect and disseminate information about who is connected to whom. For example, within a given application, GUI controls (or widgets) can appear in different forms and locations in different dialog boxes, and they may interact in different ways. For instance, pressing a button in a Continue dialog box may result in very different behavior than pressing the same button in a Print dialog box. This information
can be kept in a Mediator for each type of dialog box. The Mediator collects the controls it needs and arranges their interconnections.
Observer Pattern
The Observer pattern defines a relationship between objects so that when one changes its state, all the others are notified accordingly. There is usually an identifiable single publisher of new state, and many subscribers who wish to receive it. It a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
The Observer pattern is, like the Mediator pattern, composed of two classes. The Subject is a class whose objects change their state at an independent rate.
The Observer pattern is widely used in blog sites and various software systems— Flickr, cyber-dating web sites, and Microsoft Updates are a few of the places where it is applied. It also has a formal face as the “publish/subscribe” model and the “Model-View-Controller” (MVC) architectural pattern.
We can make use of events and delegates in C# to achieve this.
The observer pattern is used when:
• There are aspects to an abstraction that can vary independently.
• Changes in one object need to be propagated to a selection of other objects, not all of them.
• The object sending the changes does not need to know about the receivers.
Mediator and Observer Pattern Comparison
As the examples suggest, Mediator and Observer are very similar patterns. Mailing lists, chat rooms, and blogs all involve communication between individuals who actively sign upto the activity. The difference is that the Mediator centralizes the communication between colleagues, whereas the Observer distributes control of information by differentiating between subjects (publishers) and observers (subscribers).
Visitor Pattern
The Visitor pattern defines and performs new operations on all the elements of an existing structure, without altering its classes. The Visitor pattern is intended for object structures, so it is often used in conjunction with the Composite pattern. The Composite pattern is responsible for setting up the multilevel structure on which the Visitor pattern then operates.
Use the Visitor pattern when
• You have a class hierarchy that is effectively sealed.
• There are many distinct operations to perform on it.
• The operations are orthogonal to the core purpose of the types in the hierarchy.
• You need the flexibility to define new operations over time.
If a framework is designed like this, we can add additional logic without affecting the original class. Here some logic is separated from the main class. This looks similar to the strategy pattern. In strategy we have one context or a single logical data on which multiple algorithms operate. In the previous questions we have explained the fundamentals of strategy and visitor. So let’s understand the same by using examples which we have understood previously. In strategy we have a single context and multiple algorithms work on it. Figure ‘Strategy’ shows how we have a one data context and multiple algorithm work on it. In visitor we have multiple contexts and for every context we have an algorithm.
Interpreter Pattern
The Interpreter pattern supports the interpretation of instructions written in a language or notation defined for a specific purpose. The notation is precise and can be defined in terms of a grammar. It provides a way to include language elements in a program.
The Interpreter pattern is coded up from scratch wherever there is a simple grammar to parse and interpret. For more complex grammars, such as those that describe programming languages or .NET APIs, parsing tools can be employed to set up the object structure. The corresponding Interpret methods can still be successfully written from scratch. In the Mirrors example, the System.Xml API from .NET provides the parser. In compilers, there are special parser generator tools that construct a
parse tree from a grammar. Many domain-specific languages define their rules in terms of XML and rely on interpreters to activate them. For example, the Windows Vista operating system, in conjunction
with Visual Studio, interprets XML for GUIs.
Momento Pattern
This pattern is used to capture an object’s internal state and save it externally so that it can be restored later.
Example: In computer games, we save at the check points and exit. We can load the same state later when we come back.
The Memento pattern is used extensively in scientific computing to save the state of long-running computations; in computer games to save the state of play over a matter of hours or days; and in graphics toolkits to preserve the state of a display while objects are being moved around.










Recent Comments