Home Java javaTutorial java design pattern mediator pattern

java design pattern mediator pattern

Mar 18, 2017 am 11:56 AM

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);
}
Copy after login

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

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 + "]");
 }
}
Copy after login

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

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);
}
Copy after login

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

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);
   }
  }
 }
}
Copy after login

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("来呀, 来互相伤害呀!!!");
 }
}
Copy after login

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

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 of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to use the Redis cache solution to efficiently realize the requirements of product ranking list? How to use the Redis cache solution to efficiently realize the requirements of product ranking list? Apr 19, 2025 pm 11:36 PM

How does the Redis caching solution realize the requirements of product ranking list? During the development process, we often need to deal with the requirements of rankings, such as displaying a...

See all articles