MEMENTO PATTERN

Memento pattern is one of the behavioral design patterns. 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.

Memento pattern is implemented with two objects – Originator and Caretaker. Originator is the object whose state needs to be saved and restored and it uses an inner class to save the state of Object. The inner class is called Memento and its private, so that it can’t be accessed from other objects.

Caretaker is the helper class that is responsible for storing and restoring the Originator’s state through Memento object. Since Memento is private to Originator, Caretaker can’t access it and it’s stored as an Object within the caretaker.

One of the best real life examples is the text editors where we can save its data anytime and use undo to restore it to previous saved state. We will implement the same feature and provide a utility where we can write and save contents to a File anytime and we can restore it to last saved state. For simplicity, I will not use any IO operations to write data into file.

When to use the Memento Pattern:

Use the Memento Pattern in the following cases:

  • A snapshot of (some portion of) an object’s state must be saved so that it can be restored to that state later, and
  • A direct interface to obtaining the state would expose implementation details and break the object’s encapsulation

Memento Pattern in JDK:

  • java.util.Date
  • java.io.Serializable

INTERPRETER PATTERN

Interpreter pattern is one of the behavioral design patterns and 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.

To implement interpreter pattern, we need to create Interpreter context engine that will do the interpretation work and then we need to create different Expression implementations that will consume the functionalities provided by the interpreter context. Finally we need to create the client that will take the input from user and decide which Expression to use and then generate output for the user.

When to use the Interpreter Design Pattern

Use the Interpreter pattern when there is a language to interpret, and you can represent statements in the language as abstract syntax trees. The Interpreter pattern works best when

  • The grammar is simple. For complex grammars, the class hierarchy for the grammar becomes large and unmanageable. Tools such as parser generators are a better alternative in such cases. They can interpret expressions without building abstract syntax trees, which can save space and possibly time.
  • Efficiency is not a critical concern. The most efficient interpreters are usually not implemented by interpreting parse trees directly but by first translating them into another form. For example, regular expressions are often transformed into state machines. But even then, the translator can be implemented by the Interpreter pattern, so the pattern is still applicable.

Interpreter Design Pattern in JDK:

  • java.util.Pattern
  • java.text.Normalizer
  • java.text.Format

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.

The logic for iteration is embedded in the collection itself and it helps client program to iterate over them easily. 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. An Iterator object contains public methods to allow a client object to navigate through the list of objects within the container.

Iterator

  • Defines an interface for accessing and traversing elements.

ConcreteIterator

  • Implements the Iterator interface.
  • Keeps track of the current position in the traversal of the aggregate.

Aggregate

  • Defines an interface for creating an Iterator object.

ConcreteAggregate

  • Implements the Iterator creation interface to return an instance of the proper ConcreteIterator.

When to use the Iterator Design Pattern:

Use the Iterator pattern:

  • To access an aggregate object’s contents without exposing its internal representation.
  • To support multiple traversals of aggregate objects.
  • To provide a uniform interface for traversing different aggregate structures (that is, to support polymorphic iteration).
  • Iterator pattern is useful when you want to provide a standard way to iterate over a collection and hide the implementation logic from client program.

Iterator Pattern in JDK:

  • java.util.Iterator
  • java.util.Enumeration

STATE PATTERN

State design pattern is used when an Object change its behavior when it’s internal state changes.

The state of an object can be defined as its exact condition at any given point of time, depending on the values of its properties or attributes. The set of methods implemented by a class constitutes the behavior of its instances. Whenever there is a change in the values of its attributes, we say that the state of an object has changed.

When a Context object is first created, it initializes itself with its initial State object. This State object becomes the current State object for the context. By replacing the current State object with a new State object, the context transitions to a new state. When an application object makes a call to a Context method (behavior), it forwards the method call to its current State object.

Context: Defines the interface of interest to clients. Maintains an instance of a ConcreteState subclass that defines the current state.

State: Defines an interface for encapsulating the behavior associated with a particular state of the Context.

ConcreteState subclasses: Each subclass implements a behavior associated with a state of the Context.

In the state pattern, we have a Context class, and this class has a State reference to a Concrete State instance. The State interface declares particular methods that represent the behaviors of a particular state. Concrete States implement these behaviors. By changing a Context’s Concrete State, we change its behavior. In essence, in the state pattern, a class (the Context) is supposed to behave like different classes depending on its state. The state pattern avoids the use of switch and if statements to change behavior.

Example:

package com.myjavablog.behavioural.state;

public interface MobileState {

public void getState();
}

package com.myjavablog.behavioural.state;

public class Ringing implements MobileState {
@Override
public void getState() {
System.out.println("Mobile in Ringing state");
}
}

package com.myjavablog.behavioural.state;

public class Vibrate implements MobileState {
@Override
public void getState() {
System.out.println("Mobile in Vibrate mode");
}
}

package com.myjavablog.behavioural.state;

public class Silent implements MobileState {
@Override
public void getState() {
System.out.println("Mobile in Silent mode");
}
}

package com.myjavablog.behavioural.state;

public class MobileContext implements MobileState {

private MobileState mobileState;

public MobileContext(MobileState mobileState) {
this.mobileState = mobileState;
}

public void setMobileState(MobileState mobileState) {
this.mobileState = mobileState;
}

@Override
public void getState()
{
mobileState.getState();
}
}

package com.myjavablog.behavioural.state;

public class StatePatternTest {

public static void main(String[] args) {

MobileContext context = new MobileContext(new Ringing());
context.getState();
context.getState();
context.setMobileState(new Vibrate());
context.getState();
context.getState();
context.getState();
context.setMobileState(new Silent());
context.getState();
context.getState();

}
}

Output:

Mobile in Ringing state
Mobile in Ringing state
Mobile in Vibrate mode
Mobile in Vibrate mode
Mobile in Vibrate mode
Mobile in Silent mode
Mobile in Silent mode

The benefits of using State pattern to implement polymorphic behavior is clearly visible, the chances of error are less and it’s very easy to add more states for additional behavior making it more robust, easily maintainable and flexible. Also State pattern helped in avoiding if-else or switch-case conditional logic in this scenario.

When to use the State Design Pattern:

Use the State pattern in either of the following cases:

  • An object’s behavior depends on its state, and it must change its behavior at run-time depending on that state.
  • Operations have large, multipart conditional statements that depend on the object’s state. This state is usually represented by one or more enumerated constants. Often, several operations will contain this same conditional structure. The State pattern puts each branch of the conditional in a separate class. This lets you treat the object’s state as an object in its own right that can vary independently from other objects.

State Design Pattern in Java:

  • javax.faces.lifecycle.LifeCycle#execute ()

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. For example, think of a Shopping cart where we can add different type of items (Elements), when we click on checkout button, it calculates the total amount to be paid. Now we can have the calculation logic in item classes or we can move out this logic to another class using visitor pattern. So using visitor pattern we can move out logics to another class.

The Visitor pattern allows the operation to be defined without changing the class of any of the objects in the collection. To accomplish this, the Visitor pattern suggests defining the operation in a separate class referred to as a visitor class. This separates the operation from the object collection that it operates on. For every new operation to be defined, a new visitor class is created. Since the operation is to be performed across a set of objects, the visitor needs a way of accessing the public members of these objects.

Following components are involved in visitor pattern-

Visitor: Declares a Visit operation for each class of ConcreteElement in the object structure. The operation’s name and signature identifies the class that sends the Visit request to the visitor. That lets the visitor determine the concrete class of the element being visited. Then the visitor can access the element directly through its particular interface.

ConcreteVisitor: Implements each operation declared by Visitor. Each operation implements a fragment of the algorithm defined for the corresponding class of object in the structure. ConcreteVisitor provides the context for the algorithm and stores its local state. This state often accumulates results during the traversal of the structure.

Element: Defines an Accept operation that takes a visitor as an argument.

ConcreteElement: Implements an Accept operation that takes a visitor as an argument.

ObjectStructure:

Can enumerate its elements.

  • May provide a high-level interface to allow the visitor to visit its elements.
  • May either be a composite or a collection such as a list or a set.

To implement visitor pattern, first of all we will create different type of items (Elements) to be used in shopping cart.

Example:

package com.myjavablog.behavioural.visitor;

public interface ShoppingCartElement {

//accept method takes Visitor argument
public int accept(ShoppingCartVisitor visitor);
}

Let’s create some concrete classes for different types of item.

package com.myjavablog.behavioural.visitor;

public class Book implements ShoppingCartElement {

private int price;
private String isbnNumber;

public Book(int price, String isbnNumber) {
this.price = price;
this.isbnNumber = isbnNumber;
}

public int getPrice() {
return price;
}

public String getIsbnNumber() {
return isbnNumber;
}

@Override
public int accept(ShoppingCartVisitor visitor) {
return visitor.visit(this);
}
}

package com.myjavablog.behavioural.visitor;

public class Fruit implements ShoppingCartElement {

private int pricePerKg;
private int weight;
private String name;

public Fruit(int pricePerKg, int weight, String name) {
this.pricePerKg = pricePerKg;
this.weight = weight;
this.name = name;
}

public int getPricePerKg() {
return pricePerKg;
}

public int getWeight() {
return weight;
}

public String getName() {
return name;
}

@Override
public int accept(ShoppingCartVisitor visitor) {
return visitor.visit(this);
}
}

We have visit () method for different type of items in Visitor interface that will be implemented by concrete visitor class.

package com.myjavablog.behavioural.visitor;

public interface ShoppingCartVisitor {

int visit(Book book);
int visit(Fruit fruit);
}

Now we will implement visitor interface and every item will have its own logic to calculate the cost.

package com.myjavablog.behavioural.visitor;

public class ShoppingCartVisitorImpl implements ShoppingCartVisitor {
@Override
public int visit(Book book) {
int cost = 0;
//Apply discount if book price is greator than 50
if(book.getPrice() > 50){
cost = book.getPrice() - 5;
}else{
cost = book.getPrice();
}
System.out.println("Book IBSN Number: "+ book.getIsbnNumber() +" Cost : "+ cost );
return cost;
}

@Override
public int visit(Fruit fruit) {
int cost =0;

cost = fruit.getPricePerKg() * fruit.getWeight();
System.out.println("Fruit Name: "+ fruit.getName() +" Cost: "+ cost);
return cost;
}
}

Let’s see how we can use it in client applications.

package com.myjavablog.behavioural.visitor;

public class VisitorPatternTest {

public static void main(String[] args) {

ShoppingCartElement[] items = new ShoppingCartElement[]{new Book(100, "You can win"),
new Fruit(100, 2, "Apple" ), new Book(200, "Five Point Someone"),
new Fruit(40, 4, "Gauva")};

System.out.println("Total cost: "+ VisitorPatternTest.calculatePrice(items));
}

public static int calculatePrice(ShoppingCartElement[] items){

ShoppingCartVisitor visitor = new ShoppingCartVisitorImpl();
int sum = 0;

for(ShoppingCartElement element : items){
sum = sum + element.accept(visitor);
}

return sum;
}
}

Output:

Book IBSN Number: You can win Cost : 95
Fruit Name: Apple Cost: 200
Book IBSN Number: Five Point Someone Cost : 195
Fruit Name: Gauva Cost: 160
Total cost: 650

The benefit of this pattern is that if the logic of operation changes, then we need to make change only in the visitor implementation rather than doing it in all the item classes.

When to use the Visitor Design Pattern:

Use the Visitor pattern when:

  • An object structure contains many classes of objects with differing interfaces, and you want to perform operations on these objects that depend on their concrete classes.
  • Many distinct and unrelated operations need to be performed on objects in an object structure, and you want to avoid “polluting” their classes with these operations. Visitor lets you keep related operations together by defining them in one class. When the object structure is shared by many applications, use Visitor to put operations in just those applications that need them.
  • The classes defining the object structure rarely change, but you often want to define new operations over the structure. Changing the object structure classes requires redefining the interface to all visitors, which is potentially costly. If the object structure classes change often, then it’s probably better to define the operations in those classes.

Visitor Design Pattern in JDK:

  • javax.lang.model.type.TypeMirror and javax.lang.model.type.TypeVisitor
  • javax.lang.model.element.Element and javax.lang.model.element.ElementVisitor

COMMAND PATTERN

The command pattern is a behavioral object design pattern. In the command pattern, a Command interface declares a method for executing a particular action. Concrete Command classes implement the execute () method of the Command interface, and this execute () method invokes the appropriate action method of a Receiver class that the Concrete Command class contains. The Receiver class performs a particular action. A Client class is responsible for creating a Concrete Command and setting the Receiver of the Concrete Command. An Invoker class contains a reference to a Command and has a method to execute the Command.

In the command pattern, the invoker is decoupled from the action performed by the receiver. The invoker has no knowledge of the receiver. The invoker invokes a command, and the command executes the appropriate action of the receiver. Thus, the invoker can invoke commands without knowing the details of the action to be performed. In addition, this decoupling means that changes to the receiver’s action don’t directly affect the invocation of the action.

The command pattern can be used to perform ‘undo’ functionality. In this case, the Command interface should include an unexecuted () method.

In other words, it’s 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. The client program creates the receiver object and then attaches it to the Command. Then it creates the invoker object and attaches the command object to perform an action. Now when client program executes the action, it’s processed based on the command and receiver object.

To understand command design pattern we should understand the associated key terms like client, command, command implementation, invoker, and receiver.

  • Command is an interface with execute method. It is the core of contract.
  • A client creates an instance of a command implementation and associates it with a receiver.
  • An invoker instructs the command to perform an action.
  • A Command implementation’s instance creates a binding between the receiver and an action.
  • Receiver is the object that knows the actual steps to perform the action. Any class may serve as a Receiver.

Example:

package com.myjavablog.behavioural.command;

//Command interface with an execute method
public interface Command {
public void execute();
}

package com.myjavablog.behavioural.command;

//Lunch is a receiver
public class Lunch {

public void makeLunch(){
System.out.println("Lunch is being made");
}
}

package com.myjavablog.behavioural.command;

//LunchCommand implements Command. It contains reference to Lunch ,a receviver.
//Its execute method invokes appropriate action on receiver
public class LunchCommand implements Command{

Lunch lunch;

public LunchCommand(Lunch lunch){
this.lunch = lunch;
}

@Override
public void execute() {
lunch.makeLunch();
}
}

package com.myjavablog.behavioural.command;

//Dinner is a receiver
public class Dinner {

public void makeDinner()
{
System.out.println("Dinner is being made");
}
}

package com.myjavablog.behavioural.command;

//DinnerCommand also implements Command. It contains reference to Dinner ,a receviver.
//Its execute method invokes appropriate action on receiver
public class DinnerCommand implements Command{

Dinner dinner;

public DinnerCommand(Dinner dinner){
this.dinner = dinner;
}

@Override
public void execute()
{
dinner.makeDinner();
}
}

package com.myjavablog.behavioural.command;

//MealInvoker is invoker class
//It contains reference to command to invoke
//Its invoke method calls execute method of command
public class MealInvoker {

Command command;

public MealInvoker(Command command){
this.command = command;
}

public void setCommand(Command command){
this.command = command;
}

public void invoke(){
command.execute();
}

}

package com.myjavablog.behavioural.command;

public class CommandPatternDemo {

public static void main(String[] args) {

Lunch lunch = new Lunch(); //Receiver
Command lunchCommand = new LunchCommand(lunch); //Concrete command

Dinner dinner = new Dinner(); //Receiver
Command dinnerCommand = new DinnerCommand(dinner); //Concrete command

MealInvoker mealInvoker = new MealInvoker(lunchCommand); //invoker
mealInvoker.invoke();

mealInvoker.setCommand(dinnerCommand);
mealInvoker.invoke();

}
}

Output:

Lunch is being made
Dinner is being made

 

When to use the Command Design Pattern:

Use the Command pattern when you want to:

  • Parameterize objects by an action to perform.
  • Support undo. The Command’s Execute operation can store state for reversing its effects in the command itself. The Command interface must have an added Un-execute operation that reverses the effects of a previous call to Execute. Executed commands are stored in a history list. Unlimited-level undo and redo is achieved by traversing this list backwards and forwards calling Un-execute and Execute, respectively.
  • Structure a system around high-level operations built on primitives operations. Such a structure is common in information systems that support transactions. The Command pattern offers a way to model transactions. Commands have a common interface, letting you invoke all transactions the same way. The pattern also makes it easy to extend the
    system with new transactions.

Command Pattern JDK Example:

  • Runnable Interface (java.lang.Runnable) and Swing Action (javax.swing.Action) uses command pattern.

STRATEGY PATTERN

The Strategy pattern is useful when there is a set of related algorithms and a client object needs to be able to dynamically pick and choose an algorithm from this set that suits its current need. The Strategy pattern suggests keeping the implementation of each of the algorithms in a separate class. Each such algorithm encapsulated in a separate class is referred to as a strategy. An object that uses a Strategy object is often referred to as a context object.

In other words, 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.

The strategy pattern is one way that composition can be used as an alternative to subclassing. Rather than providing different behaviors via subclasses overriding methods in super classes, the strategy pattern allows different behaviors to be placed in Concrete Strategy classes which share the common Strategy interface. A Context object contains a reference to a Strategy. By changing the Context’s Strategy, different behaviors can be obtained.

Example:

package com.myjavablog.behavioural.strategy;

public interface Strategy {

public void sort(int[] numbers);
}

package com.myjavablog.behavioural.strategy;

public class Context {

private Strategy strategy;

Context(Strategy strategy){
this.strategy = strategy;
}

public void arrange(int[] input) {
strategy.sort(input);
}
}

package com.myjavablog.behavioural.strategy;

public class BubbleSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("Sorted using bubble sort!!");
}
}

package com.myjavablog.behavioural.strategy;

public class MergeSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("Sorted using Merge sort!!");
}
}

package com.myjavablog.behavioural.strategy;

public class InsertionSort implements Strategy {
@Override
public void sort(int[] numbers) {
System.out.println("Sorted using Insertion sort!!");
}
}

package com.myjavablog.behavioural.strategy;

public class StrategyPatternTest {

public static void main(String[] args) {

int[] var = {2, 4, 1, 3 , 9, 6};

//We can provide any strategy for sorting
Context ctx = new Context(new BubbleSort());
ctx.arrange(var);

//We can change the strategy without changing Context class
ctx = new Context(new MergeSort());
ctx.arrange(var);
}
}

Output:

Sorted using bubble sort!!
Sorted using Merge sort!!

When to use the Strategy Design Pattern:

Use the Strategy pattern when:

  • Many related classes differ only in their behavior. Strategies provide a way to configure a class with one of many behaviors.
  • You need different variants of an algorithm. For example, you might define algorithms reflecting different space/time trade-offs. Strategies can be used when these variants are implemented as a class hierarchy of algorithms.
  • An algorithm uses data that clients shouldn’t know about. Use the Strategy pattern to avoid exposing complex, algorithm-specific data structures.
  • A class defines many behaviors, and these appear as multiple conditional statements in its operations. Instead of many conditionals, move related conditional branches into their own Strategy class.

Strategy Pattern in JDK:

  • java.util.Comparator#compare ()
  • javax.servlet.http.HttpServlet
  • javax.servlet.Filter#doFilter ()

OBSERVER PATTERN

In observer design pattern multiple observer objects registers with a subject for change notification. When the state of subject changes, it notifies the observers. Objects that listen or watch for change are called observers and the object that is being watched for is called subject.

Pattern involved is also called as publish-subscribe pattern.

  • Subject provides interface for observers to register and unregister themselves with the subject.
  • Subject knows who its subscribers are.
  • Multiple observers can subscribe for notifications.
  • Subject publishes the notifications.
  • Subject just sends the notification saying the state has changed. It does not pass any state information.
  • Once the notification is received from subject, observers call the subject and get data that is changed.

The above last two points are not strictly followed in observer design pattern implementation. Along with the notification, state is also passed in some implementation so that the observer need not query back to know the status. It is better not to do this way.

There are four participants in the Observer pattern:

* Subject, which is used to register observers. Objects use this interface to register as observers and also to remove themselves from being observers.

* Observer defines an updating interface for objects that should be notified of changes in a subject. All observers need to implement the Observer interface. This interface has a method update (), which gets called when the Subject’s state changes.

* ConcreteSubject, stores the state of interest to ConcreteObserver objects. It sends a notification to its observers when its state changes. A concrete subject always implements the Subject interface. The notifyObservers () method is used to update all the current observers whenever the state changes.

* ConcreateObserver maintains a reference to a ConcreteSubject object and implements the Observer interface. Each observer registers with a concrete subject to receive updates.

Java provides inbuilt platform for implementing Observer pattern through java.util.Observable class and java.util.Observer interface. However it’s not widely used because the implementation is really simple and most of the times we don’t want to end up extending a class just for implementing Observer pattern as java doesn’t provide multiple inheritances in classes.

Example:
Let us take a blog and subscriber example for observer design pattern sample implementation. Assume that there is a blog and users register to that blog for update. When a new article is posted in the blog, it will send update to the registered users saying a new article is posted. Then the user will access the blog and read the new article posted. In this example, blog is the subject and user is the observer.

package com.myjavablog.behavioural.observer;

public interface Subject {

public void registerObserver(Observer observer);
public void notifyObserver();
public void unregisterObserver(Observer observer);
public Object getUpdate();
}

package com.myjavablog.behavioural.observer;

public interface Observer {

public void update();
public void setSubject(Subject sub);
}

package com.myjavablog.behavioural.observer;

import java.util.ArrayList;
import java.util.List;

//Concrete Subject
public class Blog implements Subject {

List<Observer> observerList;
private boolean stateChange;

public Blog(){
this.observerList = new ArrayList<>();
stateChange = false;
}

@Override
public void registerObserver(Observer observer) {
observerList.add(observer);
}

@Override
public void notifyObserver() {
if(stateChange){
for(Observer observer: observerList){
observer.update();
System.out.println("Observer notified!!");
}
}
}

@Override
public void unregisterObserver(Observer observer) {
observerList.remove(observer);
}

@Override
public Object getUpdate() {

Object changedState = null;

//Should have a logic to send state change to the querying observer
if(stateChange){
changedState = "Observer Design Pattern";
}

return changedState;
}

public void postNewArticle(){
stateChange = true;
notifyObserver();
}
}

package com.myjavablog.behavioural.observer;

//Concrete Observer
public class User implements Observer {

private String article;
private Subject blog;

@Override
public void update() {
System.out.println("State change reported by subject");
article = (String) blog.getUpdate();
}

@Override
public void setSubject(Subject blog) {
this.blog = blog;
article = "No new article!";
}

public String getArticle(){
return article;
}
}

package com.myjavablog.behavioural.observer;

public class ObserverPatternTest {

public static void main(String[] args) {
Blog blog = new Blog();
User user1 = new User();
User user2 = new User();
blog.registerObserver(user1);
blog.registerObserver(user2);
user1.setSubject(blog);
user2.setSubject(blog);
System.out.println(user1.getArticle());
blog.postNewArticle();
System.out.println(user1.getArticle());
}
}

Output:

No new article!
State change reported by subject
Observer notified!!
State change reported by subject
Observer notified!!
Observer Design Pattern

When to use the Observer Pattern:

Use the Observer pattern in any of the following situations:

  • When an abstraction has two aspects, one dependent on the other. Encapsulating these aspects in separate objects lets you vary and reuse them independently.
  • When a change to one object requires changing others, and you don’t know how many objects need to be changed?
  • When an object should be able to notify other objects without making assumptions about who these objects are. In other words, you don’t want these objects tightly coupled.

Usage in Java:

  • java.util.EventListener in Swing
  • javax.servlet.http.HttpSessionBindingListener
  • javax.servlet.http.HttpSessionAttributeListener

 

 

CHAIN OF RESPONSIBILITY

Chain of responsibility pattern is used to achieve lose coupling in software design where a request from client is passed to a chain of objects to process them. Then the object in the chain will decide themselves who will be processing the request and whether the request is required to be sent to the next object in the chain or not.

When there is more than one objects that can handle or fulfill a client request, the pattern recommends giving each of these objects a chance to process the request in some sequential order. Applying the pattern in such a case, each of these potential handlers can be arranged in the form of a chain, with each object having a reference to the next object in the chain. The first object in the chain receives the request and decides either to handle the request or to pass it on to the next object in the chain. The request flows through all objects in the chain one after the other until the request is handled by one of the handlers in the chain or the request reaches the end of the chain without getting processed.

Let’s see the example of chain of responsibility pattern in JDK and then we will proceed to implement a real life example of this pattern. We know that we can have multiple catch blocks in a try-catch block code. Here every catch block is kind of a processor to process that particular exception. So when any exception occurs in the try block its send to the first catch block to process. If the catch block is not able to process it, it forwards the request to next object in chain i.e. next catch block. If even the last catch block is not able to process it, the exception is thrown outside of the chain to the calling program.

Other examples are ATM money dispenser, Servlet Filter and finally java’s own Exception Handling mechanism. We know exception handling better than anybody else and we are daily living with it. This qualifies as the best example for chain of responsibility.

Example:

In ATM Dispense machine, the user enters the amount to be dispensed and the machine dispense amount in terms of defined currency bills such as 50$, 20$, 10$ etc. If the user enters an amount that is not multiples of 10, it throws error.

package com.myjavablog.behavioural.COR;

//This class is a request object.
public class Number {

private int number;

public int getNumber(){
return number;
}

public Number(int number){
this.number = number;
}
}

package com.myjavablog.behavioural.COR;

//This interface acts as a chain link
public interface Chain {

public void setNext(Chain nextInChain);
public void process(Number request);
}

package com.myjavablog.behavioural.COR;

public class PositiveNumberProcessor implements Chain {

private Chain nextInChain;

@Override
public void setNext(Chain c) {
this.nextInChain = c;
}

@Override
public void process(Number request) {

if(request.getNumber() > 0){
System.out.println("PositiveNumberProcessor : "+ request.getNumber());
}else {
nextInChain.process(request);
}
}
}

package com.myjavablog.behavioural.COR;

public class NegativeNumberProcessor implements Chain {

private Chain nextInChain;

@Override
public void setNext(Chain c) {
this.nextInChain = c;
}

@Override
public void process(Number request) {

if(request.getNumber() < 0){
System.out.println("NegativeNumberProcessor : "+ request.getNumber());
}else {
nextInChain.process(request);
}
}
}

package com.myjavablog.behavioural.COR;

public class ZeroProcessor implements Chain {

private Chain nextInChain;

@Override
public void setNext(Chain c) {
this.nextInChain = c;
}

@Override
public void process(Number request) {

if(request.getNumber() == 0){
System.out.println("ZeroProcessor : "+ request.getNumber());
}else {
nextInChain.process(request);
}
}
}

package com.myjavablog.behavioural.COR;

public class CORPatternTest {

public static void main(String[] args) {

//Configure chain of responsibility
Chain c1 = new NegativeNumberProcessor();
Chain c2 = new ZeroProcessor();
Chain c3 = new PositiveNumberProcessor();
c1.setNext(c2);
c2.setNext(c3);

//Calling chain of responsibility
c1.process(new Number(99));
c1.process(new Number(-76));
c1.process(new Number(0));
c1.process(new Number(100));

}
}

Output:

PositiveNumberProcessor : 99
NegativeNumberProcessor : -76
ZeroProcessor : 0
PositiveNumberProcessor : 100

When to use the Chain of Responsibility Pattern:

Use Chain of Responsibility when

  • More than one object may handle a request, and the handler isn’t known a priority. The handler should be ascertained automatically.
  • You want to issue a request to one of several objects without specifying the receiver explicitly.
  • The set of objects that can handle a request should be specified dynamically.

Chain of Responsibility Pattern Examples in JDK:

  • java.util.logging.Logger#log ()
  • javax.servlet.Filter#doFilter ()

MEDIATOR PATTERN

Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently.

Mediator design pattern is used to provide a centralized communication medium between different objects in a system.

Rather than interacting directly with each other, objects ask the Mediator to interact on their behalf which results in reusability and loose coupling. It encapsulates the interaction between the objects and makes them independent from each other. This allows them to vary their interaction with other objects in a totally different way by implementing a different mediator. The Mediator helps to reduce the complexity of the classes. Each object no longer has to know in detail about how to interact with the other objects. The coupling between objects goes from tight and brittle to loose and agile.

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. Mediator pattern focuses on providing a mediator between objects for communication and help in implementing lose-coupling between objects.

Air traffic controller is a great example of mediator pattern where the airport control room works as a mediator for communication between different flights. Mediator works as a router between objects and it can have its own logic to provide way of communication.

The major participants of the Mediator Pattern are:

  • Mediator: Defines an interface for communicating with Colleague objects.
  • ConcreteMediator: Implements co-operative behavior by coordinating Colleague objects. It also knows and maintains its colleagues.
  • Colleague Classes: Each Colleague class knows its Mediator objects. Each colleague communicates with its mediator whenever it would have otherwise communicated with another colleague.

Example:

package com.myjavablog.behavioural.mediator;

public interface IMediator {

public void talk();
public void fight();
public void registerA(ColleagueA a);
public void registerB(ColleagueB b);
}

package com.myjavablog.behavioural.mediator;

public class ConcreteMediator implements IMediator {

ColleagueA talk;
ColleagueB fight;

@Override
public void talk() {
System.out.println("Mediator is talking");
//Talk colleague doing some stuff
}

@Override
public void fight() {
System.out.println("Mediator is fighting");
//Fight colleague doing some stuff
}

@Override
public void registerA(ColleagueA a) {
this.talk =a;
}

@Override
public void registerB(ColleagueB b) {
this.fight =b;
}
}

package com.myjavablog.behavioural.mediator;

public abstract class Colleague {
IMediator mediator;
public abstract void doSomething();
}

package com.myjavablog.behavioural.mediator;

public class ColleagueA extends Colleague{

ColleagueA(IMediator mediator){
this.mediator = mediator;
this.mediator.registerA(this);
}

@Override
public void doSomething() {
this.mediator.talk();
}
}

package com.myjavablog.behavioural.mediator;

public class ColleagueB extends Colleague{

ColleagueB(IMediator mediator){
this.mediator = mediator;
this.mediator.registerB(this);
}

@Override
public void doSomething() {
this.mediator.fight();
}
}

package com.myjavablog.behavioural.mediator;

public class MediatorPatternTest {

public static void main(String[] args) {

IMediator mediator = new ConcreteMediator();

ColleagueA talkColleague = new ColleagueA(mediator);
talkColleague.doSomething();

ColleagueB fightColleague = new ColleagueB(mediator);
fightColleague.doSomething();

}
}

Output:

Mediator is talking
Mediator is fighting

 

When to use the Mediator Pattern:

  • A set of objects communicate in well-defined but complex ways. The resulting interdependencies are unstructured and difficult to understand.
  • Reusing an object is difficult because it refers to and communicates with many other objects.
  • A behavior that’s distributed between several classes should be customizable without a lot of sub-classing.

 

Mediator Pattern in JDK:

  • java.util.Timer class scheduleXXX () methods.
  • java Concurrency Executor execute () method.
  • java.lang.reflect.Method invoke () method.

 

 

Bitnami