Behavioral design patterns

Behavioral design patterns deal with the communication of objects. Patterns of this type vary with the assignment of responsibilities to the communicating objects and the way they interact with each other.
Do check the creational patterns and the design patterns catalogue.

Chain of responsibility
Intent of this pattern is to create a chain of objects in which each of the objects has its own distinct reponsibility. It’s widely employed in request processing as this allows decoupling requests from the processing bit. Object in the chain could skip the request and pass it on the next in the chain or decide to process a part of the reponse. It also provides the flexibility to add objects to the chain independently. A good example of this is the filter chain in web containers.

Sample code – Chain of responsibility in C#. ETL has been taken as an example chain comprising of 3 objects – extract, transform and load.
Command pattern
Command pattern represents a request which carries parameters and associated information on its execution context. It decouples the request (sender) and the processing (receiver). It allows commands to queued and invoked in a controllable manner. Command objects can be passed down to a processing chain of objects (chain of responsibility). In a typical implementation, there are 3 roles associated with this pattern – Command object, Invoker which accepts the command from the client triggering its execution and the receiver which is the processing unit.

Sample code – Command pattern implementation in C#.

Interpreter pattern
This is suited for implementing grammers for a computer language. Idea is to represent every token as a class. This idea becomes cumbersome for language with large vocabulary as a class is required for every token. Inpretation of the grammer forms a syntax tree which is a composite pattern. This pattern is rarely used as there are better methods available to parse laguages.

Sample code – Interpreter implementation in C#.
Mediator pattern
Purpose of mediator pattern is to facilitate communication among objects through a mediator. It promotes loose coupling among participating objects. Chat Forum application is a good example of this. Instead of connecting individual users, they are made to connect via a hub. Another real world example could be the role of ATC (Air Traffic Controller) in airports. ATC acts as a mediator in communicating with in-bound and out-bound flights sharing the runway.

Sample code – Mediator implementation in C#.
Iterator pattern
Iterator pattern models the sequential access over a read-only snapshot of the collection. It’s widely used and usually built in to the development kits of all programming languages.

Sample code – Iterator pattern implementation in C#.
Observer pattern
It’s also called as subscribe/publish or event listener pattern. Purpose of this pattern is to notify certain change in state (event) of the subject (observable) to the observers. Observers register themselves to the subject creating a dependency. When the event happens in subject, the observers are notified by the subject. Typical example of this is the popular Model-View-Controller (MVC) breed of patterns used in presentation layer technologies. Model represents the observable and views are the observers. When the model changes, view are updated.
Visitor pattern
Purpose of the visitor pattern is to add a functionality to an existing data structure without modifying it. Functionality to be added is modeled as a visitor which exposes a visit method. Data structure has an accept method which accepts the visitor and calls the visit method of visitor passing it’s reference. Visitor uses the reference to add functionality to manipulate the data structure.

Visitor pattern is useful in modeling collections (data structure in object oriented world) in libraries where there is a chance to add custom functionality by the consuming code.

Quick example code – Visitor pattern in C#

  • Customer object is the data structure.
  • Print Visitor access customer object and prints its details to console.
Template pattern
Template pattern allows defining the skeleton of a program and force the subclasses to provide the implementation of the individual steps. It’s suited for implementing algorithms with the invariant steps in the abstract class and delegating the variable steps to the sub-class. Thus the template pattern allows sub-classes to define the internal behaviour of the algorithm.

Code sample – Template pattern in C#. Usecase – ETL. ETL process is defined in the abstract parent class ETL. StructuredDataETL is a sub-class of ETL and provides the behavior for the Extract, Transfer and Load steps.

Strategy pattern
Strategy pattern allows to choose and apply an algorithm from the family of algorithms at the run time. It helps modeling a family of algorithms which could be applied interchangeably.

Code sample – Strategy pattern in C#..

  • Family of algorithms – IAlgorithm with 2 implementations AdditionStrategy and SubtractionStrategy
  • One of the above algorithms applied the context at the run time to work upon on 2 integers
State pattern
State pattern lets change its behavior based on in its internal state (defined by a class level variable). State object is often implemented as singleton. It is similar to strategy pattern but differ in purpose and how often the state is changed. In case of strategy pattern, the binding is done once but with state pattern, binding is changed often at runtime.

Refer C# sample on state pattern.

Momento pattern
Purpose of momento pattern is to save the state (class level variables) of an object in another object. This mechanism helps in restoring the state of the original object on need. Object whose state to be saved is called originator and the object where the state is saved is called momento. Structure of momento has to be similar to the sturucture of the originator. There is a role called care taker which manages the momento objects. Momento is similar to command pattern as both of them can be passed around. Often, momento along with command pattern can be used to accomplish undo operation.

Sample code – C# implementation of momento pattern.

Null Object
Null object is a substitute for the absence of an object. Most of the languages represent a null condition. Null object pattern proposes to wrap null condition in an object called Null object which does nothing. It helps avoid the popular NPE (NUll Pointer Exceptions). Java 8 Optional follow Null object pattern.
Scheduled Task pattern
The intent of this pattern is defer the execution of the object until meeting certain conditions such as timestamp. Most of the computing frameworks have this mechanism to schedule tasks

Leave a Reply

Your email address will not be published. Required fields are marked *