Mediator Pattern

Imagine having a number of objects interacting with each other directly. As the number of objects increases, this type of direct interaction can lead to a mess. It also reduces the scope for reuse.

The Mediator pattern can be used to design a controlled, coordinated communication model for a group of objects (colleagues), eliminating the need for objects to refer to each other directly.
The Mediator pattern suggests abstracting all object interaction details into a separate class, referred to as a Mediator, who knows how the objects interact. Objects no more interact directly but all the messages go through Mediator.

Structure

Mediator can be implemented in different ways.

mediator.jpeg

Sometimes ConcreteMediator extends participating objects instead of their interface.

GoF:

mediator2.jpeg

The simple way:

mediator3.jpeg

Sample Code

//this acts as mediator
public class StockExchange {
    public void doTransaction(){
    }
 
    public void getPrice(){
    }
}
 
//does not talk to seller directly
public class Buyer {
    StockExchange med;
    public void doTransaction(){
    }
}
 
//does not talk to buyer directly
public class Seller {
    StockExchange med;
    public void doTransaction(){
    }
}

Another example:

public class Mediator {
    public  void storeMessage(String msg  ) {
    }
 
    public synchronized String retrieveMessage() {
        return 
    }
}
public class Producer {
    Mediator med;
    public void produce(){
        //put msg into the mediator
    }
}
public class Consumer {
    Mediator med;
    public void consume(){
        //get msg from the mediator
    }
}

Consequences:

  • Decouples colleague objects
  • Mediator can become too complicated

Related Patterns

  • Mediator is different from Facade since Facade provides a higher level interface but Mediator does not. Also Facade is not known to the subsystem components but all the objects know about Mediator.
  • Colleagues can communicate with mediator using Observer Pattern.
  • Mediator is similar to wrapper as it becomes a bold component of the system unlike bridge which is transient.
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License