Tuesday, 17 March 2015

Mediator Design Pattern Implementation

Mediator Design Pattern


Question:- What is Mediator Design Pattern?
This design pattern falls under Behavioral design pattern. This(Mediator) pattern is used to reduce communication complexity between multiple objects or classes. It helps to centralize communication between objects into a mediator object. With the help of this pattern communication happens with the help of mediator so we achieves loose coupling.

As per GOF:- “Allows loose coupling by encapsulating the way disparate sets of objects interact and communicate with each other. Allows for the actions of each object set to vary independently of one another.”

Question:- When to use Mediator design pattern?
Answer:- If we need to centralize complex communications and control between related objects then this design pattern can be used.
Advantages:-
  • It helps to centralize control to manipulate participating objects and it also helps to simplfies maintenance of the system by centralizing control logic.
  • It helps to increases the reusability of the objects supported by the Mediator by decoupling them from the system.

In Mediator Design pattern, the classes that communicate with the mediator are known as Colleagues. The mediator implementation is known as the Concrete Mediator. Colleagues know about their mediator, and the mediator also knows about its colleagues.

Mediator example in JDK API
  • java.lang.reflect.Method#invoke()
  • java.util.Timer (all scheduleXXX() methods)
  • java.util.concurrent.Executor#execute()
  • java.util.concurrent.ExecutorService (the invokeXXX() and submit() methods)
  • java.util.concurrent.ScheduledExecutorService (all scheduleXXX() methods)


Live examples of Mediator design pattern

Mediator example in Real world :- Air traffic controller (ATC) is a mediator between multiple flights. It helps in communication between flights and co-oridates/controls landing & take-off. Two flights need not interact directly and there should not be any dependency between them. This dependency is solved by the mediator ATC.

We will see a sample program to implement mediator design pattern.

Messenger Interface as Mediator

package com.gaurav.designpattern.mediator;

/**
 * @author Gaurav
 *
 */
public interface Messenger {
    void addContact(Contact contact);
    
    public void sendMessage(Contact contact, String msg);
}

Contact class as Colleague component

package com.gaurav.designpattern.mediator;

/**
 * @author Gaurav
 *
 */
public abstract class Contact {
protected Messenger chatMediator;
    protected String name;
     
    public Contact(String name, Messenger messenger){
        this.chatMediator = messenger;
        this.name=name;
    }
     
    public abstract void send(String msg);
     
    public abstract void receive(String msg);
}


MessengerImpl class as Concrete Mediator

package com.gaurav.designpattern.mediator;

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

/**
 * @author Gaurav
 *
 */

public class MessengerImpl implements Messenger{
private List<Contact> contacts;
    
    public MessengerImpl(){
        this.contacts=new ArrayList<>();
    }
     
    @Override
    public void addContact(Contact contact){
        this.contacts.add(contact);
    }
     
    @Override
    public void sendMessage(Contact contact, String msg) {
        for(Contact userContact : this.contacts){
            if(userContact != contact){
                userContact.receive(msg);
            }
        }
    }
}


ContactImpl class as Concrete Colleague


package com.gaurav.designpattern.mediator;

/**
 * @author Gaurav
 *
 */
public class ContactImpl extends Contact{
public ContactImpl(String name, Messenger messenger) {
super(name, messenger);
}

@Override
public void send(String message) {
System.out.println("Sender "+this.name+" has sent message which is : = "+message);
chatMediator.sendMessage(this, message);
}

@Override
public void receive(String message) {
System.out.println("Receiver "+this.name+" has received message which is : = "+message);
}
}

MediatorDesignPatternDemo class as Caller


package com.gaurav.designpattern.mediator;

/**
 * @author Gaurav
 * 
 */
public class MediatorDesignPatternDemo {
public static void main(String args[]) {
Messenger messenger = new MessengerImpl();
Contact contact1 = new ContactImpl("Gaurav", messenger);
Contact contact2 = new ContactImpl("Sunita", messenger);
Contact contact3 = new ContactImpl("Aaditya", messenger);
Contact contact4 = new ContactImpl("Shivam", messenger);

messenger.addContact(contact1);
messenger.addContact(contact2);
messenger.addContact(contact3);
messenger.addContact(contact4);

contact1.send("Welcome to everyone in chat messenger");
}
}


Result:-

Sender Gaurav has sent message which is : = Welcome to everyone in chat messenger
Receiver Sunita has received message which is : = Welcome to everyone in chat messenger
Receiver Aaditya has received message which is : = Welcome to everyone in chat messenger
Receiver Shivam has received message which is : = Welcome to everyone in chat messenger


No comments:

Post a Comment