Home  >  Article  >  Java  >  java design pattern mediator pattern

java design pattern mediator pattern

高洛峰
高洛峰Original
2017-03-18 11:56:531408browse

Mediator Pattern

Object-oriented design encourages the distribution of behavior among various objects. This distribution may result in many connections between objects. In the worst case, each One object needs to know about all other objects.

Although dividing a system into many objects can enhance reusability, the proliferation of interconnections between objects can reduce its reusability. A large number The connection relationship makes it impossible for an object to work without the assistance of other objects (the system appears as an indivisible whole). At this time, it is very difficult to make any major changes to the system behavior. Because the behavior is distributed among many objects , the result is that many subclasses have to be defined to customize the behavior of the system. From this we introduce the mediator object Mediator:

java design pattern mediator pattern

Through the mediator object, the network structure can be The system is transformed into a star structure with an intermediary as the center. Each specific object no longer has a direct relationship with another object, but is mediated through the intermediary object. The introduction of the intermediary object also makes the system structure not affected by the intermediary object. The introduction of new objects has resulted in a large number of modifications.

Mediator pattern: Also known as the mediator pattern, a mediator object (Mediator) is used to encapsulate the interaction of a series of objects, so that each object can interact with each other without having to show it. References, thereby loosening the coupling and allowing them to independently change their interactions:

java design pattern mediator pattern

(Image source: Design Patterns: The Foundation of Reusable Object-Oriented Software) Tips : Each Colleague only knows the existence of the Mediator, and does not need to know whether other Colleagues exist (otherwise how to decouple it). It only needs to send the message to the Mediator, and then the Mediator forwards it to other Colleagues (the Mediator stores all Colleague relationships, and Only the Mediator knows how many/which Colleague).

Mode implementation

The United Nations forwards statements from various countries and mediates relations between countries:
Countries send and receive messages to the United Nations Security Council, and the Security Council mediates between countries' Forward requests appropriately to achieve collaborative behavior:

java design pattern mediator pattern

##Colleague

Abstract colleague class, define the public methods of each colleague:

/**
 * @author jifang
 * @since 16/8/28 下午4:22.
 */
public abstract class Country {
 
 protected UnitedNations mediator;
 
 private String name;
 
 public Country(UnitedNations mediator, String name) {
  this.mediator = mediator;
  this.name = name;
 }
 
 public String getName() {
  return name;
 }
 
 protected abstract void declare(String msg);
 
 protected abstract void receive(String msg);
}

-------------------------------------------------- ----------------------------------

ConcreteColleague

Concrete colleague class:

•Each colleague class knows its mediator object.
•Each colleague object communicates with its mediator when it needs to communicate with other colleagues.

class USA extends Country {
 
 public USA(UnitedNations mediator, String name) {
  super(mediator, name);
 }
 
 @Override
 public void declare(String msg) {
  mediator.declare(this, msg);
 }
 
 @Override
 public void receive(String msg) {
  System.out.println("美国接收到: [" + msg + "]");
 }
}
 
class Iraq extends Country {
 
 public Iraq(UnitedNations mediator, String name) {
  super(mediator, name);
 }
 
 @Override
 public void declare(String msg) {
  mediator.declare(this, msg);
 }
 
 @Override
 public void receive(String msg) {
  System.out.println("伊拉克接收到: [" + msg + "]");
 }
}
 
class China extends Country {
 
 public China(UnitedNations mediator, String name) {
  super(mediator, name);
 }
 
 @Override
 public void declare(String msg) {
  mediator.declare(this, msg);
 }
 
 @Override
 public void receive(String msg) {
  System.out.println("中国接收到: [" + msg + "]");
 }
}

------- -------------------------------------------------- -----------------------

Mediator

Abstract mediator: Define an interface for communicating with each colleague object :

public abstract class UnitedNations {
 
 protected List<Country> countries = new LinkedList<>();
 
 public void register(Country country) {
  countries.add(country);
 }
 
 public void remove(Country country) {
  countries.remove(country);
 }
 
 protected abstract void declare(Country country, String msg);
}

--------------------------------------------- -------------------------------------

ConcreteMediator

Specific intermediary:

•Understand and maintain its various colleagues;
•Achieve collaborative behavior by coordinating each colleague object (receiving messages from colleagues and issuing commands to specific colleagues).

class UnitedNationsSecurityCouncil extends UnitedNations {
 
 /**
  * 安理会在中间作出调停
  *
  * @param country
  * @param msg
  */
 @Override
 protected void declare(Country country, String msg) {
  for (Country toCountry : countries) {
   if (!toCountry.equals(country)) {
    String name = country.getName();
    toCountry.receive(name + "平和的说: " + msg);
   }
  }
 }
}

If If there is no extension, then the Mediator can be combined with the ConcreteMediator.

•Client

public class Client {
 
 @Test
 public void client() {
  UnitedNations mediator = new UnitedNationsSecurityCouncil();
 
  Country usa = new USA(mediator, "美国");
  Country china = new China(mediator, "中国");
  Country iraq = new Iraq(mediator, "伊拉克");
 
  mediator.register(usa);
  mediator.register(china);
  mediator.register(iraq);
 
  usa.declare("我要打伊拉克, 谁管我跟谁急!!!");
  System.out.println("----------");
  china.declare("我们强烈谴责!!!");
  System.out.println("----------");
  iraq.declare("来呀, 来互相伤害呀!!!");
 }
}

----------------------- -------------------------------------------------- -------

Summary

The emergence of Mediator reduces the coupling between Colleagues, allowing each Colleague and Mediator to be independently changed and reused, due to how objects collaborate By eliminating abstraction, treating mediation as an independent concept and encapsulating it in an object, the focus of attention shifts from the behavior of the objects themselves to the interaction between them, so that it can be viewed from a more macro perspective. System.


•Applicability

The mediator model is easy to apply in the system, and it is also easy to misuse it in the system. When the system has a complex object group with "many-to-many" interaction When using a mediator, do not rush to use a mediator. It is best to first reflect on whether the design of the system is reasonable. Since ConcreteMediator controls centralization, it turns the interaction complexity into the complexity of the mediator, making the mediator more complex than any other mediator. ConcreteColleague is complex. The Mediator pattern is recommended in the following situations:
◦ A set of objects communicate in a well-defined but complex way. The resulting interdependencies are cluttered and difficult to understand.
◦ One object references other There are many objects and they communicate directly with these objects, making it difficult to reuse the object.
◦I want to customize a behavior that is distributed in multiple classes, but do not want to generate too many subclasses.

•Related Patterns
◦The difference between Facade and mediator is that it abstracts an object subsystem, thus providing a more convenient interface. Its protocol is one-way, that is, Facade object Make requests to this subsystem class, but not vice versa. On the contrary, Mediator provides collaborative behaviors that are not supported or cannot be supported by each Colleague object, and the protocol is multi-directional.
◦Colleague can use the Observer pattern to communicate with Mediator.

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to the intermediary pattern of java design patterns, please pay attention to the PHP Chinese website!

Related articles:

Detailed introduction to the code for implementing the Mediator pattern in Java

Introduction to the chain of responsibility pattern of Java design patterns

Introduction to Java design pattern proxy mode (Proxy mode)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn