There is no such thing as perfect programming, but we shouldn’t be discouraged because programming is a constant pursuit of perfection.

  1. Intent defines an object that encapsulates the interaction of a group of objects, reduces coupling between objects, does not need to display references between objects, and can individually change the way objects interact.
  2. The class diagram

  3. The instance
// Interface Mediator{void sendMessage(String message); String receiveMessage(); } class MediatorImpl1 implements Mediator{ private String message; @Override public void sendMessage(String message) { this.message = message; } @Override public String receiveMessage() { return message; Class SimpleMediator{public static void showMessage(Me Me, String message){ System.out.println(me.getName() + " send " + message); } } class Me{ private String name; private String message; / / send a message through the Mediator, decoupling public void sendMessage () {SimpleMediator. ShowMessage (this message); } public void sendMessage1(Mediator mediator){ mediator.sendMessage(message); System.out.println("send : " + message); } public void receiveMessage1(Mediator mediator){ String re = mediator.receiveMessage(); System.out.println("re : " + re); } public static Me create(){ return new Me(); } public String getName() { return name; } public Me setName(String name) { this.name = name; return this; } public String getMessage() { return message; } public Me setMessage(String message) { this.message = message; return this; }}Copy the code
  1. test
class MediatorTest{ public static void main(String[] args) { Me me1 = Me.create().setName("h1").setMessage("hello m2"); Me me2 = Me.create().setName("h2").setMessage("hello m1"); System.out.println(" first type -- "); me1.sendMessage(); me2.sendMessage(); System.out.println(" second kind -- "); MediatorImpl1 mediatorImpl1 = new MediatorImpl1(); System.out.println("me1 send: "); me1.sendMessage1(mediatorImpl1); System.out.println("me2 receive: "); me2.receiveMessage1(mediatorImpl1); }}Copy the code

Running results:

H1 send Hello m2 H2 send Hello M1 Me1 Send: hello m2 ME2 Receive: re: hello m2Copy the code

Want to see more? Please visit:Design patterns