Java Design Patterns Mediator Patterns

Introduction

Mediator Patterns define an object that encapsulates how a set of objects interacts.

Example

abstract class Mediator {
   public abstract void send(Employee frd, String msg);
}
abstract class Employee {
   protected Mediator mediator;
   public String name;
   public Employee(Mediator _mediator) {
      mediator = _mediator;// w  w  w  . jav  a 2  s  . c om
   }
}
class TeamMediator extends Mediator {
   private Tester tester;
   private Developer developer;
   private Boss boss;

   public void setFriend1(Tester friend1) {
      this.tester = friend1;
   }

   public void setFriend2(Developer friend2) {
      this.developer = friend2;
   }

   public void setBoss(Boss boss) {
      this.boss = boss;
   }

   @Override
   public void send(Employee frd, String msg) {
      if (frd == tester) {
         developer.notify(msg);
         boss.notify(tester.name + " sends message to " + developer.name);
      }
      if (frd == developer) {
         tester.notify(msg);
         boss.notify(developer.name + " sends message to " + tester.name);
      }
      if (frd == boss) {
         tester.notify(msg);
         developer.notify(msg);
      }
   }
}

class Tester extends Employee {
   public Tester(Mediator mediator, String name) {
      super(mediator);
      this.name = name;
   }

   public void send(String msg) {
      mediator.send(this, msg);
   }

   public void notify(String msg) {
      System.out.println(name+" gets message: " + msg);
   }
}
class Developer extends Employee {
   public Developer(Mediator mediator, String name) {
      super(mediator);
      this.name = name;
   }

   public void send(String msg) {
      mediator.send(this, msg);
   }

   public void notify(String msg) {
      System.out.println(name +" gets message: " + msg);
   }
}
class Boss extends Employee {
   public Boss(Mediator mediator, String name) {
      super(mediator);
      this.name = name;
   }

   public void send(String msg) {
      mediator.send(this, msg);
   }
   public void notify(String msg) {
      System.out.println("Message: " + msg);
   }
}

public class Main {
   public static void main(String[] args) {
      TeamMediator m = new TeamMediator();

      Tester tester = new Tester(m, "Tester 1");
      Developer dev = new Developer(m, "Dev 1");
      Boss boss = new Boss(m, "Boss");

      m.setFriend1(tester);
      m.setFriend2(dev);
      m.setBoss(boss);

      tester.send("testing");
      dev.send("coding");
      boss.send("managin");

   }
}



PreviousNext

Related