当前位置:网站首页>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
边栏推荐
- Rapid development project -vscode plug-in
- How to create a subtype like relationship between two generic classes when the classes are generic related
- [hackthebox] dancing (SMB)
- LabVIEW displays Unicode characters
- Pytorch read / write file
- Webassembly learning - dynamic linking
- What is the method of connection query in MySQL
- 【HackTheBox】dancing(SMB)
- String differences between different creation methods
- 如何创建 robots.txt 文件?
猜你喜欢

What are the circular statements of MySQL

I came from a major, so I didn't want to outsource
![[hackthebox] dancing (SMB)](/img/bb/7bf81004b9cee80ae49bb0c0c2b810.png)
[hackthebox] dancing (SMB)

ROS URDF model is parsed into KDL tree

MySQL column to row conversion without Union

Inftnews | metauniverse technology will bring a new shopping experience

IDEA修改jvm内存

Analysis of moudo Network Library

Build a simple website by yourself

SQL two columns become multi row filter display
随机推荐
How to keep database and cache consistent
JDBC learning
MySQL column to row conversion without Union
1017 a divided by B
Practical part: solving the function conflict between swagger and user-defined parameter parser
Libuv library overview and comparison of libevent, libev and libuv (Reprint)
大神们 在富函数的open中从mysql连接池里取连接 连接池初始化是20个 如果富函数的并行度是1
[C language] explain the thread recycling function pthread_ join
The people's Bank of China printed and distributed the notice on supporting cross-border RMB settlement of new foreign trade formats
Daily practice - February 15, 2022
女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了
剑指 Offer II 040. 矩阵中最大的矩形
科班出身,结果外包都不要
1016 part a+b
Project development culture
Gocd is good, but talk about Jenkins
How to merge upstream and downstream SQL data records
JVM_ 16_ Garbage collector
Emotional changes need to be controlled
【HackTheBox】dancing(SMB)