GOF Design Patterns - Part 4 - Behavioral Design Patterns
Sushant Kumar Tarway
Experienced Product Manager | Agile & SAFe 6.0 Practitioner | Microservices, APIs, Containerization, Web Development| Product Strategy and User-Centric Design, API - first and Cloud Native focussed on TDD/BDD
Behavioral Design Patterns
In starting post of this GOF Design Pattern Series, I described what a Design Pattern is and why do we need Design patterns and what are different types of Design Patterns. In subsequent post I wrote about Creational Design Patterns, Structural Design Patterns
In this post, I will deep dive a step further and will discuss briefly on different types of Behavioral Design Patterns.
Behavioral patterns provide solution for the better interaction between objects and how to provide lose coupling and flexibility to extend easily.
Template Method Pattern
Template Method is used to create a method stub and deferring some of the steps of implementation to the subclasses. Template method defines the steps to execute an algorithm and it can provide default implementation that might be common for all or some of the subclasses. Suppose we want to provide an algorithm to build a house. The steps need to be performed to build a house are – building foundation, building pillars, building walls and windows. The important point is that we can’t change the order of execution because we can’t build windows before building the foundation. So in this case we can create a template method that will use different methods to build the house.
Mediator Pattern
Mediator design pattern is used to provide a centralized communication medium between different objects in a system. Mediator design pattern is very helpful in an enterprise application where multiple objects are interacting with each other. If the objects interact with each other directly, the system components are tightly-coupled with each other that make maintainability cost higher and not flexible to extend easily. Air traffic controller (ATC) is a mediator between flights. It helps in communication between flights and co-ordinates/controls landing, take-off. Two flights need not interact directly and there is no dependency between them. This dependency is solved by the mediator ATC. If ATC is not there all the flights have to interact with one another and managing the show will be very difficult and things may go wrong.
Chain of Responsibility Pattern
The idea of the Chain Of Responsibility is that it avoids coupling the sender of the request to the receiver, giving more than one object the opportunity to handle the request. This process of delegation appears quite frequently in the real world where there is one interface for the customer to go through. One example could be a bank, where an application that you send in to the bank branch may be handled by one particular department. Another example is a vending machine, where you can put in any coin, but the coin is passed on to the appropriate receptacle to determine the amount that the coin is worth.
Observer Pattern
Observer design pattern is useful when you are interested in the state of an object and want to get notified whenever there is any change. In observer pattern, the objects that watch on the state of another object are called Observer and the object that is being watched is called Subject. In Observer design pattern multiple observer objects register with a subject for change notification. When the state of subject changes, it notifies the observers. Objects that listen or watch for changes are called observers and the object that is being watched for is called subject. Pattern involved is also called as publish-subscribe pattern. Model view controller (MVC) architecture’s core uses the observer design pattern.
Strategy Pattern
Strategy pattern is used when we have multiple algorithms for a specific task and client decides the actual implementation to be used at runtime. Strategy pattern is also known as Policy Pattern. We define multiple algorithms and let client application pass the algorithm to be used as a parameter. One of the best example of this pattern is Collections.sort() method that takes Comparator parameter. Based on the different implementations of Comparator interfaces, the Objects are getting sorted in different ways
Command Pattern
Command Pattern is used to implement lose coupling in a request-response model. In command pattern, the request is send to the invoker and invoker passes it to the encapsulated command object. Command object passes the request to the appropriate method of Receiver to perform the specific action. Let’s say we want to provide a File System utility with methods to open, write and close file and it should support multiple operating systems such as Windows and UNIX. To implement our File System utility, first of all we need to create the receiver classes that will actually do all the work. Since we code in terms of java interfaces, we can have FileSystemReceiver interface and its implementation classes for different operating system flavors such as Windows, UNIX, and Solaris etc.
State Pattern
State design pattern is used when an Object change its behavior based on its internal state. If we have to change the behavior of an object based on its state, we can have a state variable in the Object and use if-else condition block to perform different actions based on the state. State pattern is used to provide a systematic and lose-coupled way to achieve this through Context and State implementations. State design pattern provides a mechanism to change behavior of an object based on the object’s state. Think of our kitchen mixer, which has a step down motor inside and a control interface. Using that knob we can increase / decrease the speed of the mixer. Based on speed state the behavior changes.
Visitor Pattern
Visitor pattern is used when we have to perform an operation on a group of similar kind of Objects. With the help of visitor pattern, we can move the operational logic from the objects to another class. Shopping in the supermarket is common example, where the shopping cart is your set of elements. When you get to the checkout, the cashier acts as a visitor, taking the disparate set of elements (your shopping), some with prices and others that need to be weighed, in order to provide you with a total.
Interpreter Pattern
It is used to define a grammatical representation for a language and provides an interpreter to deal with this grammar. The best example of this pattern is java compiler that interprets the java source code into byte code that is understandable by JVM. Google Translator is also an example of interpreter pattern where the input can be in any language and we can get the output interpreted in another language.
Iterator Pattern
Iterator pattern in one of the behavioral pattern and it’s used to provide a standard way to traverse through a group of Objects. Iterator pattern is widely used in Java Collection Framework where Iterator interface provides methods for traversing through a collection. Iterator pattern is not only about traversing through a collection; we can provide different kind of iterators based on our requirements. Iterator pattern hides the actual implementation of traversal through the collection and client programs just use iterator methods.
Memento Pattern
Memento design pattern is used when we want to save the state of an object so that we can restore later on. Memento pattern is used to implement this in such a way that the saved state data of the object is not accessible outside of the object, this protects the integrity of saved state data. object kept as a reminder of a person or event” is what Wikipedia says for the word “memento”. I cannot write about memento design pattern without mentioning Christopher Nolan’s movie Memento. The hero of Memento has a type of amnesia and he tries to backtrack events to trace the killer. Memento movie and memento design pattern are synonymous. Memento design pattern helps to restore an object’s state to it previous state. Memento design pattern is used to implement the undo operation. This is done by saving the current state of the object as it changes state.