当前位置:网站首页>Mediator pattern
Mediator pattern
2022-06-29 04:23:00 【Change with affection】
Intermediary model
Intermediary model (Mediator Pattern) It is used to reduce the communication complexity between multiple objects and classes . This pattern provides a mediation class , This class usually handles communication between different classes , And support loose coupling , Make the code easy to maintain . The intermediary model belongs to the behavioral model .
- Using a mediation object to encapsulate a A series of object interactions . Mediators make it unnecessary for objects to explicitly refer to each other , So that the coupling is loose , And they can change their interaction independently
- The intermediary model belongs to the behavioral model , Make the code easy to maintain
- such as MVC Pattern ,C (Controller controller ) yes M (Model Model ) and V (View View ) Intermediary of , In front and back of the interaction between the role of a middleman
Case a
- Smart home includes all kinds of devices , alarm clock 、 Coffee machine 、 The TV 、 Curtains, etc
- When it comes to watching TV , Devices can work together , Automatic preparation for watching TV , For example, the process is : The alarm rings > The coffee machine starts making coffee > The curtains fall automatically > The TV is on

Traditional way of problem analysis - When the electrical objects have various state changes , The calling relationship between each other will be more complex .
- various Electrical objects are connected to each other , You have me , I have you. , Not conducive to loose coupling .
- Messages passed between electrical objects ( Parameters ), It's easy to get confused
- When When the system adds a new electrical object , Or when the process changes , Code maintainability 、 The scalability is not ideal
Case 2 : Intermediary model

// Colleague abstract class
public abstract class Colleague {
private Mediator mediator;
public String name;
public Colleague(Mediator mediator, String name) {
this.mediator = mediator;
this.name = name;
}
public Mediator GetMediator() {
return this.mediator; }
public abstract void SendMessage(int stateChange);
}
// Specific colleagues
public class Alarm extends Colleague {
// Constructors
public Alarm(Mediator mediator, String name) {
super(mediator, name);
// Creating Alarm When a colleague is an object , Put yourself in ConcreteMediator In the object [ aggregate ]
mediator.Register(name, this);
}
public void SendAlarm(int stateChange) {
SendMessage(stateChange);
}
@Override
public void SendMessage(int stateChange) {
// Of the mediator object invoked getMessage
this.GetMediator().GetMessage(stateChange, this.name);
}
}
public class CoffeeMachine extends Colleague {
public CoffeeMachine(Mediator mediator, String name) {
super(mediator, name);
mediator.Register(name, this);
}
@Override
public void SendMessage(int stateChange) {
this.GetMediator().GetMessage(stateChange, this.name); }
public void StartCoffee() {
System.out.println("It's time to startcoffee!"); }
public void FinishCoffee() {
System.out.println("After 5 minutes!");
System.out.println("Coffee is ok!");
SendMessage(0);
}
}
public class Curtains extends Colleague {
public Curtains(Mediator mediator, String name) {
super(mediator, name);
mediator.Register(name, this);
}
@Override
public void SendMessage(int stateChange) {
this.GetMediator().GetMessage(stateChange, this.name); }
public void UpCurtains() {
System.out.println("I am holding Up Curtains!"); }
}
public class TV extends Colleague {
public TV(Mediator mediator, String name) {
super(mediator, name);
mediator.Register(name, this);
}
@Override
public void SendMessage(int stateChange) {
this.GetMediator().GetMessage(stateChange, this.name); }
public void StartTv() {
System.out.println("It's time to StartTv!"); }
public void StopTv() {
System.out.println("StopTv!"); }
}
public abstract class Mediator {
// Will be given to the intermediary object , Add to the collection
public abstract void Register(String colleagueName, Colleague colleague);
// receive messages , Specific coworkers send out
public abstract void GetMessage(int stateChange, String colleagueName);
public abstract void SendMessage();
}
// Specific intermediary classes
public class ConcreteMediator extends Mediator {
// aggregate , Put in all the coworkers
private HashMap<String, Colleague> colleagueMap;
private HashMap<String, String> interMap;
public ConcreteMediator() {
colleagueMap = new HashMap<String, Colleague>();
interMap = new HashMap<String, String>();
}
@Override
public void Register(String colleagueName, Colleague colleague) {
colleagueMap.put(colleagueName, colleague);
if (colleague instanceof Alarm) {
interMap.put("Alarm", colleagueName);
} else if (colleague instanceof CoffeeMachine) {
interMap.put("CoffeeMachine", colleagueName);
} else if (colleague instanceof TV) {
interMap.put("TV", colleagueName);
} else if (colleague instanceof Curtains) {
interMap.put("Curtains", colleagueName);
}
}
// The core method of specific intermediaries
//1. According to the news , Complete the task accordingly
//2. The mediator is in this method , Coordinate with specific colleagues , To complete the task
@Override
public void GetMessage(int stateChange, String colleagueName) {
// Processing alarm messages
if (colleagueMap.get(colleagueName) instanceof Alarm) {
if (stateChange == 0) {
((CoffeeMachine) (colleagueMap.get(interMap
.get("CoffeeMachine")))).StartCoffee();
((TV) (colleagueMap.get(interMap.get("TV")))).StartTv();
} else if (stateChange == 1) {
((TV) (colleagueMap.get(interMap.get("TV")))).StopTv();
}
} else if (colleagueMap.get(colleagueName) instanceof CoffeeMachine) {
((Curtains) (colleagueMap.get(interMap.get("Curtains"))))
.UpCurtains();
} else if (colleagueMap.get(colleagueName) instanceof TV) {
// If TV Find out the news
} else if (colleagueMap.get(colleagueName) instanceof Curtains) {
// If it's a message from a curtain , Here to deal with ...
}
}
@Override
public void SendMessage() {
}
}
public class ClientTest {
public static void main(String[] args) {
// Create a mediator object
Mediator mediator = new ConcreteMediator();
// establish Alarm And join in ConcreteMediator Object's HashMap
Alarm alarm = new Alarm(mediator, "alarm");
// Created CoffeeMachine object , and And add to ConcreteMediator Object's HashMap
CoffeeMachine coffeeMachine = new CoffeeMachine(mediator, "coffeeMachine");
// establish Curtains , and And add to ConcreteMediator Object's HashMap
Curtains curtains = new Curtains(mediator, "curtains");
TV tV = new TV(mediator, "TV");
// Let the alarm clock send a message
alarm.SendAlarm(0);
coffeeMachine.FinishCoffee();
alarm.SendAlarm(1);
}
}
summary
- Multiple classes are coupled to each other , Will form a network , Use the mediator pattern to separate the mesh into star structures , Decoupling
- Reduce class dependency , Reduced coupling , In line with the Dimitar principle
- Intermediaries take more responsibility , Once an intermediary has a problem , The whole system will be affected
- If Improper design , The intermediary object itself becomes too complex , This is actually used , Pay special attention to
边栏推荐
- 【HackTheBox】dancing(SMB)
- Remediation for Unsafe Cryptographic Encryption
- Developer scheme · environmental monitoring equipment (Xiaoxiong school IOT development board) connected to graffiti IOT development platform
- Hot renewal process
- Ansible最佳实践之Playbook不同上下文提权Demo
- Analysis of moudo Network Library
- JVM_ 16_ Garbage collector
- 剑指 Offer II 040. 矩阵中最大的矩形
- Path and LD_ LIBRARY_ Example of path usage
- Blue Bridge Cup ruler method
猜你喜欢
![[new function] ambire wallet integrates Metis network](/img/29/8a8c0cd40c51cef1174ee59706d4c9.png)
[new function] ambire wallet integrates Metis network

LabVIEW显示Unicode字符

Redis cache penetration, cache breakdown, cache avalanche

赚钱的5个层次,你在哪一层?

Why is the test post a giant pit? The 8-year-old tester told you not to be fooled

From zero to one, I will teach you to build a "search by text and map" search service (I)

Log in to the MySQL database and view the version number on the command line

MySQL column to row conversion without Union

Inftnews | metauniverse technology will bring a new shopping experience

Error accessing database
随机推荐
MySQL subquery
Canoe- how to parse messages and display information in the trace window (use of program node and structure type system variables)
大神们 在富函数的open中从mysql连接池里取连接 连接池初始化是20个 如果富函数的并行度是1
Sword finger offer II 040 Largest rectangle in matrix
[laravel series 8] out of the world of laravel
使用AssetStudio/UnityStudio UABE等
What is the dry goods microservice architecture? What are the advantages and disadvantages?
Here comes Wi Fi 7. How strong is it?
Airflow 2.2.3 containerized installation
1015 theory of virtue and talent
选对学校,专科也能进华为~早知道就好了
Error accessing database
SQL database stored procedure writing method
Daily practice - February 15, 2022
Anaconda自带的Spyder编辑器启动报错问题
NotImplementedError: Could not run torchvision::nms
iNFTnews | 元宇宙技术将带来全新的购物体验
IDEA修改jvm内存
女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了
Practical part: solving the function conflict between swagger and user-defined parameter parser