Introduction to Java design pattern Mediator pattern

  • 2020-04-01 03:42:15
  • OfStack

Mediator definition: a mediation object that encapsulates a set of behaviors about an object's interactions.

Why use the Mediator mode/mediation mode

The interactions between the various objects is very much, the behavior of each object operations are dependent on each other, each other to modify an object's behavior, at the same time to modify the behavior of the other object, if you use the Mediator pattern, loose coupling between different objects can make, just concern and the relationship between the Mediator and make a many-to-many relationship became a one-to-many relationship, can reduce the complexity of system, improve can modify extensibility.

How to use the mediation pattern

First, there is an interface to define the interactive contact between the member objects:


    public interface Mediator { }

The specific implementation of Meiator and the actual implementation of interactive operations:

public class ConcreteMediator implements Mediator {
   //Suppose there are currently two members.
   private ConcreteColleague1 colleague1 = new ConcreteColleague1();
   private ConcreteColleague2 colleague2 = new ConcreteColleague2();
   ...
}

Consider another participant: members, because they are interactive, both parties need to provide some common interface, a requirement that is the same in patterns such as a Visitor Observer.

public class Colleague {
   private Mediator mediator;
   public Mediator getMediator() {
      return mediator;
   }
   public void setMediator( Mediator mediator ) {
      this.mediator = mediator;
   }
}
public class ConcreteColleague1 { }
public class ConcreteColleague2 { }

Each member must know about Mediator and contact Mediator, not the other members.

At this point, the framework of Mediator mode was completed, and it could be found that there were not many regulations on Mediator mode and the general framework was relatively simple, but the actual use was very flexible.

Mediator mode is more common in event-driven applications, such as interface design GUI, chat, message passing, etc. In the chat application, there needs to be a MessageMediator, which is specifically responsible for the adjustment of tasks between request/reponse.

MVC is a basic pattern of J2EE, and View Controller is a Mediator, which is a Mediator between the Jsp and the application on the server.


Related articles: