Mediator design pattern

Type : Behavioral Design Pattern

Summary

Mediator design pattern provides a common platform for communication between different objects.
It promotes loose coupling between interacting objects.

Details

In a complex software where number of classes interacting with each other are more, using Mediator design pattern is very useful. As mediator will reduce the complexity of objects interacting with each other to a centralized Mediator, which results in easy maintenance of code.

Mediator is similar to Observer pattern as both promotes loose coupling. Mediator is a single object though which other objects communicates. In Observer pattern we can generally have multiple observer object.

Whatsapp group, Messenger group can be considered as mediators. Users post messages to the group rather than directly to each other.
Enterprise service bus (ESB) can be considered as mediator.
Netflix app can be considered as a mediator.

Participants in mediator design pattern
Mediator
Concrete Mediator
Colleague

Advantages 

Centralizes the interaction between many objects which is easy to maintain.
Promotes decoupling the interacting objects.

Example

For our example we will consider Netflix as the mediator. Publishers can publish show directly to Netflix and users can use Netflix to get contents. Rather than the subscribers or shows directly interacting with each other they use the mediator to communicate.

Mediator - in our case it is MediatorApp
Concrete Mediator - in our case it is NetflixApp
Colleague - Subscriber


Class Diagram







Sample Code


// mediator interface
public interface MediatorApp {

  public void addSuscribers(Subscriber susc);

  public void addShow(Show show);

}



// concrete mediator
public class NetflixApp implements MediatorApp {

  private List suscribers = new ArrayList();

  public NetflixApp() {

  }

  @Override
  public void addSuscribers(Subscriber suscriber) {
    this.suscribers.add(suscriber);
  }

  @Override
  public void addShow(Show show) {
    for (Subscriber sus : suscribers) {
      sus.addMyShows(show);

    }
  }

}


// colleague
public class Show {

  String showName;

  MediatorApp mediator;

  public Show(String sn, MediatorApp mediator) {
    this.showName = sn;
    this.mediator = mediator;
  }

  @Override
  public String toString() {
    return showName;
  }
}


public class Subscriber {

  private String name;

  public Subscriber(String name) {
    this.name = name;
  }

  public void addMyShows(Show myShow) {
    System.out.println("Show " + myShow + " added for " + name);
  }

}

Comments

Popular posts from this blog

Converting Java Map to String

Difference between volatile and synchronized

Invoking EJB deployed on a remote machine