Mediator pattern (C++)

definition

Use an intermediary object to encapsulate (encapsulate changes) a series of object interactions. The intermediary makes objects not need to explicitly refer to each other (compile-time dependency -> run-time dependency), thus making them loosely coupled (managing changes), and their interactions can be changed independently.

Application Scenario

  • In the process of software construction, multiple objects often interact with each other, and a complex reference relationship is often maintained between objects. If some requirements change, this direct reference relationship will face constant changes. .
  • In this case, we can use an "intermediary object" to manage the relationship between objects, avoid the tightly coupled reference relationship between interacting objects, and better resist changes.

structure

insert image description here

code example

//Mediator.h
/****************************************************/
#ifndef MEDIATOR_H
#define MEDIATOR_H
#include <iostream>
using namespace std;
 
class User
{
    
    
public:
	User(string tname) {
    
     name = tname; };
	~User() {
    
    };
 
	string getName() {
    
     return name; };
	void setName(string tname) {
    
     name = tname; };
 
	void sendMessage(string message);
 
private:
	string name;
};
 
class ChatRoom
{
    
    
public:
	ChatRoom() {
    
    };
	~ChatRoom() {
    
    };
 
	static void showMessage(User *user, string message) {
    
    cout << " [" << user->getName() << "] : " << message << endl;};
};
 
void User::sendMessage(string message)
{
    
    
	ChatRoom::showMessage(this, message);
}


#endif
//test.cpp
/****************************************************/
#include "Mediator.h"
int main()
{
    
    
	User robert("Robert");
	User john("John");
	robert.sendMessage("Hi! John!");
	john.sendMessage("Hello! Robert!");
	
	return 0;
}

operation result

insert image description here

Summary

  • Decoupling the complex relationship between multiple objects, the Mediator mode centralizes the management of the control logic between multiple objects, changing "multiple objects are associated with each other" into "multiple objects are associated with a mediator", which simplifies system maintenance , against possible changes.
  • With the complexity of the control logic, the implementation of the Mediator concrete object may be quite complicated. At this time, the Mediator object can be decomposed.
  • The Facade mode is to decouple the (one-way) object association between systems; the Mediator mode is to decouple the (two-way) association between objects in the system.

Guess you like

Origin blog.csdn.net/weixin_47424753/article/details/132145645