行为型模式——中介者模式

中介者设计模式适用于以下情况:

• 一组对象以定义良好但复杂的方式进行通信,产生的相互依赖关系结构混乱且难以理解;

• 一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象;

• 想定制一个分布在多个类中的行为,而又不想生成太多的子类;

下面是一个中介者模式的示例程序:

cpp 复制代码
#include <iostream>
#include <string>
#include <vector>
#include <memory>

class User; // Forward declaration

// =================================================================
// Step 1: THE MEDIATOR INTERFACE
// =================================================================
// Defines how components communicate with the central manager.
class ChatRoomMediator {
public:
    virtual ~ChatRoomMediator() = default;
    
    // Sends a message from a specific sender to everyone else
    virtual void sendMessage(const std::string& message, User* sender) = 0;
};


// =================================================================
// Step 2: THE BASE COMPONENT CLASS (Colleague)
// =================================================================
// Objects that use the mediator to talk to each other.
class User {
protected:
    std::string name_;
    ChatRoomMediator& mediator_; // Reference to the central control tower

public:
    User(const std::string& name, ChatRoomMediator& mediator) 
        : name_(name), mediator_(mediator) {}
        
    virtual ~User() = default;

    std::string getName() const { return name_; }

    // Send a message out to the world (routed via the mediator)
    void send(const std::string& message) {
        std::cout << "\n[" << name_ << " sends]: " << message << "\n";
        mediator_.sendMessage(message, this);
    }

    // Receive a message coming in from the mediator
    void receive(const std::string& message, const std::string& fromWho) {
        std::cout << "  -> " << name_ << " received a message from " << fromWho << ": \"" << message << "\"\n";
    }
};


// =================================================================
// Step 3: THE CONCRETE MEDIATOR
// =================================================================
// Implements coordination logic by holding a list of all chatters.
class TextChatRoom : public ChatRoomMediator {
private:
    std::vector<User*> users_; // Tracks all active colleagues in the room

public:
    void addUser(User* user) {
        users_.push_back(user);
    }

    void sendMessage(const std::string& message, User* sender) override {
        // Broadcast the message to every user EXCEPT the person who sent it
        for (User* user : users_) {
            if (user != sender) {
                user->receive(message, sender->getName());
            }
        }
    }
};


// =================================================================
// Step 4: CLIENT CODE
// =================================================================
int main() {
    // 1. Set up the central control tower (the mediator)
    TextChatRoom codingChatRoom;

    // 2. Create users and hook them up to the central chat room
    User alice("Alice", codingChatRoom);
    User bob("Bob", codingChatRoom);
    User charlie("Charlie", codingChatRoom);

    // 3. Register users inside the mediator's tracking list
    codingChatRoom.addUser(&alice);
    codingChatRoom.addUser(&bob);
    codingChatRoom.addUser(&charlie);

    std::cout << "=== Chat Room Activity Started ===\n";

    // 4. Users send messages. Notice they never directly interact with each other!
    alice.send("Hey everyone! Are we ready for the code review?");
    bob.send("Yes, looks good to me.");

    return 0;
}

程序运行结果如下:

shell 复制代码
$ g++ -o main main.cpp
$ ./main
=== Chat Room Activity Started ===

[Alice sends]: Hey everyone! Are we ready for the code review?
  -> Bob received a message from Alice: "Hey everyone! Are we ready for the code review?"
  -> Charlie received a message from Alice: "Hey everyone! Are we ready for the code review?"

[Bob sends]: Yes, looks good to me.
  -> Alice received a message from Bob: "Yes, looks good to me."
  -> Charlie received a message from Bob: "Yes, looks good to me."
相关推荐
ShineWinsu4 小时前
对于 C++ :从 const、constexpr、auto、decltype 到 type_traits、SFINAE 与 Concepts的解析
c++
星火10244 小时前
【Groovy翻译-进阶篇】Groovy 中的设计模式
后端·设计模式·groovy
_Narcissus_4 小时前
B树概念及操作笔记(含完整代码实现)
c语言·数据结构·数据库·c++·笔记·b树·算法
筠筠喵呜喵4 小时前
解决问题:QNX平台调用glReadPixels卡滞
c++·unix
SL_staff5 小时前
风控规则如何从硬编码解耦?我们在 JVS-Rules 中的实践与思考
java·spring boot·设计模式
_Narcissus_5 小时前
B+树的概念和操作笔记(含完整代码实现)
c语言·数据结构·数据库·c++·笔记·b树·算法
aichitang20245 小时前
快乐泛函每一天!内积空间
c++·python·数学·算法·机器学习·ai·泛函分析
Ravikov5 小时前
工具开发-ESP32程序管理系统 | 具体实现(一)
c++
欧特克_Glodon6 小时前
OpenCV计算机视觉开发入门与实践<十六>:图像边框和图像轮廓
c++·人工智能·opencv·计算机视觉
小此方6 小时前
Linux加餐(一):藏在Linux中的设计模式(一)策略模式与日志
linux·设计模式·策略模式