search
HomeJavajavaTutorialjava design pattern mediator pattern

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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version