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:
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:
(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:
/** * @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); }-------------------------------------------------- ----------------------------------ConcreteColleagueConcrete 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 + "]"); } }------- -------------------------------------------------- -----------------------MediatorAbstract 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); }--------------------------------------------- -------------------------------------ConcreteMediatorSpecific 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("来呀, 来互相伤害呀!!!"); } }----------------------- -------------------------------------------------- ------- SummaryThe 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.
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

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

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

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

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]

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

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
Integrate Eclipse with SAP NetWeaver application server.

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

SublimeText3 Linux new version
SublimeText3 Linux latest version