Friday, 26 May 2017

Mediator pattern

Mediator pattern defines an object that encapsulates how a set of objects interact.

Mediator - defines the interface for communication between Colleague objects.

ConcreteMediator - implements the Mediator interface.
Implements the communication and transfer the messages between the colleague objects.

ConcreteColleague - communicates with other Colleagues through its.

Before Mediator Design Pattern

 After Mediator Design Pattern


Chat application

package designpattern.mediator;

public interface IChatMediator {
    public void sendMessage(IUser from, IUser to, String msg);

    void addUser(IUser user);

import java.util.ArrayList;
import java.util.List;
public class ChatMediator implements IChatMediator {
      private List<IUser> users;

      public ChatMediator() {
            this.users=new ArrayList<>();

      public void addUser(IUser user) {

      public void sendMessage(IUser from, IUser to, String msg) {

public abstract class IUser {
      protected IChatMediator mediator;
      protected String name;

      public IUser(IChatMediator med, String name){

      public abstract void send(IUser to, String msg);

      public abstract void receive(IUser from,String msg);

public class User extends IUser {
      public User(ChatMediator med, String name) {
            super(med, name);

      public void send(IUser to, String msg) {
            System.out.println(": Sending Message="+msg);
            mediator.sendMessage(this, to,msg);
      public void receive(IUser from, String msg) {
            System.out.println("Delivered from "" to ";

public class ChatClient {
      public static void main(String[] args) {
            ChatMediator mediator = new ChatMediator();
            IUser john = new User(mediator, "john");
            IUser micheal = new User(mediator, "micheal");
            john.send(micheal, "hello micheal!");
            micheal.send(john, "hello john!");

john: Sending Message=hello micheal!
Delivered from john to micheal
micheal: Sending Message=hello john!
Delivered from micheal to john

Mediator Pattern usage in JDK

Java Message Service (JMS) uses Mediator pattern along with Observer pattern to allow applications to subscribe and publish data to other applications.

java.util.Timer class schedule (i.e scheduleAtFixedRate) methods.

Java Concurrency Executor execute() method.

java.lang.reflect.Method invoke() method.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...