C++中的中介者模式

目录

[中介者模式(Mediator Pattern)](#中介者模式(Mediator Pattern))

实际应用

聊天室

空中交通管制系统

智能家居控制系统

总结


中介者模式(Mediator Pattern)

中介者模式是一种行为型设计模式,它定义了一个对象来封装一系列对象之间的交互。通过使用中介者模式,减少了对象之间的直接依赖,使对象的交互变得松散耦合,从而提高系统的可维护性和可扩展性。

实际应用

聊天室

-- 管理用户之间的消息传递。

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

// 中介者接口
class ChatMediator {
public:
    virtual void sendMessage(const std::string& message, class User* user) = 0;
    virtual void addUser(std::shared_ptr<User> user) = 0;
};

// 用户类
class User {
protected:
    ChatMediator& mediator;
    std::string name;
public:
    User(ChatMediator& mediator, const std::string& name) : mediator(mediator), name(name) {}
    virtual void send(const std::string& message) = 0;
    virtual void receive(const std::string& message) = 0;
    std::string getName() const { return name; }
};

// 具体中介者
class ChatRoom : public ChatMediator {
private:
    std::vector<std::shared_ptr<User>> users;
public:
    void addUser(std::shared_ptr<User> user) override {
        users.push_back(user);
    }

    void sendMessage(const std::string& message, User* user) override {
        for (const auto& u : users) {
            if (u.get() != user) {
                u->receive(message);
            }
        }
    }
};

// 具体用户
class ConcreteUser : public User {
public:
    ConcreteUser(ChatMediator& mediator, const std::string& name) : User(mediator, name) {}

    void send(const std::string& message) override {
        std::cout << name << " sends: " << message << std::endl;
        mediator.sendMessage(message, this);
    }

    void receive(const std::string& message) override {
        std::cout << name << " received: " << message << std::endl;
    }
};

// 客户端代码
int main() {
    ChatRoom chatRoom;

    auto user1 = std::make_shared<ConcreteUser>(chatRoom, "User1");
    auto user2 = std::make_shared<ConcreteUser>(chatRoom, "User2");
    auto user3 = std::make_shared<ConcreteUser>(chatRoom, "User3");

    chatRoom.addUser(user1);
    chatRoom.addUser(user2);
    chatRoom.addUser(user3);

    user1->send("Hello everyone!");
    user2->send("Hi User1!");
    user3->send("Good morning!");

    return 0;
}

空中交通管制系统

-- 管理飞机之间的通信。

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

// 中介者接口
class ATCMediator {
public:
    virtual void sendMessage(const std::string& message, class Aircraft* aircraft) = 0;
    virtual void addAircraft(std::shared_ptr<Aircraft> aircraft) = 0;
};

// 飞机类
class Aircraft {
protected:
    ATCMediator& mediator;
    std::string id;
public:
    Aircraft(ATCMediator& mediator, const std::string& id) : mediator(mediator), id(id) {}
    virtual void send(const std::string& message) = 0;
    virtual void receive(const std::string& message) = 0;
    std::string getId() const { return id; }
};

// 具体中介者
class ATC : public ATCMediator {
private:
    std::vector<std::shared_ptr<Aircraft>> aircrafts;
public:
    void addAircraft(std::shared_ptr<Aircraft> aircraft) override {
        aircrafts.push_back(aircraft);
    }

    void sendMessage(const std::string& message, Aircraft* aircraft) override {
        for (const auto& a : aircrafts) {
            if (a.get() != aircraft) {
                a->receive(message);
            }
        }
    }
};

// 具体飞机
class ConcreteAircraft : public Aircraft {
public:
    ConcreteAircraft(ATCMediator& mediator, const std::string& id) : Aircraft(mediator, id) {}

    void send(const std::string& message) override {
        std::cout << "Aircraft " << id << " sends: " << message << std::endl;
        mediator.sendMessage(message, this);
    }

    void receive(const std::string& message) override {
        std::cout << "Aircraft " << id << " received: " << message << std::endl;
    }
};

// 客户端代码
int main() {
    ATC atc;

    auto aircraft1 = std::make_shared<ConcreteAircraft>(atc, "AC1");
    auto aircraft2 = std::make_shared<ConcreteAircraft>(atc, "AC2");
    auto aircraft3 = std::make_shared<ConcreteAircraft>(atc, "AC3");

    atc.addAircraft(aircraft1);
    atc.addAircraft(aircraft2);
    atc.addAircraft(aircraft3);

    aircraft1->send("Requesting landing clearance.");
    aircraft2->send("Acknowledged. Waiting for clearance.");
    aircraft3->send("Holding pattern at 5000 feet.");

    return 0;
}

智能家居控制系统

-- 用中介者模式来管理不同设备之间的通信。

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

// 中介者接口
class SmartHomeMediator {
public:
    virtual void sendMessage(const std::string& message, class Device* device) = 0;
    virtual void addDevice(std::shared_ptr<Device> device) = 0;
};

// 设备类
class Device {
protected:
    SmartHomeMediator& mediator;
    std::string name;
public:
    Device(SmartHomeMediator& mediator, const std::string& name) : mediator(mediator), name(name) {}
    virtual void send(const std::string& message) = 0;
    virtual void receive(const std::string& message) = 0;
    std::string getName() const { return name; }
};

// 具体中介者
class SmartHomeController : public SmartHomeMediator {
private:
    std::vector<std::shared_ptr<Device>> devices;
public:
    void addDevice(std::shared_ptr<Device> device) override {
        devices.push_back(device);
    }

    void sendMessage(const std::string& message, Device* device) override {
        for (const auto& d : devices) {
            if (d.get() != device) {
                d->receive(message);
            }
        }
    }
};

// 具体设备
class Light : public Device {
public:
    Light(SmartHomeMediator& mediator, const std::string& name) : Device(mediator, name) {}

    void send(const std::string& message) override {
        std::cout << "Light " << name << " sends: " << message << std::endl;
        mediator.sendMessage(message, this);
    }

    void receive(const std::string& message) override {
        std::cout << "Light " << name << " received: " << message << std::endl;
    }
};

class Thermostat : public Device {
public:
    Thermostat(SmartHomeMediator& mediator, const std::string& name) : Device(mediator, name) {}

    void send(const std::string& message) override {
        std::cout << "Thermostat " << name << " sends: " << message << std::endl;
        mediator.sendMessage(message, this);
    }

    void receive(const std::string& message) override {
        std::cout << "Thermostat " << name << " received: " << message << std::endl;
    }
};

class SecurityCamera : public Device {
public:
    SecurityCamera(SmartHomeMediator& mediator, const std::string& name) : Device(mediator, name) {}

    void send(const std::string& message) override {
        std::cout << "Security Camera " << name << " sends: " << message << std::endl;
        mediator.sendMessage(message, this);
    }

    void receive(const std::string& message) override {
        std::cout << "Security Camera " << name << " received: " << message << std::endl;
    }
};

// 客户端代码
int main() {
    SmartHomeController controller;

    auto light = std::make_shared<Light>(controller, "Living Room");
    auto thermostat = std::make_shared<Thermostat>(controller, "Main");
    auto camera = std::make_shared<SecurityCamera>(controller, "Front Door");

    controller.addDevice(light);
    controller.addDevice(thermostat);
    controller.addDevice(camera);

    light->send("Turning on the lights.");
    thermostat->send("Setting temperature to 22 degrees.");
    camera->send("Motion detected.");

    return 0;
}

总结

中介者模式可以帮助我们将对象之间的交互封装在一个中介者对象中,从而减少对象之间的直接依赖。

相关推荐
SRY122404192 小时前
javaSE面试题
java·开发语言·面试
李元豪3 小时前
【智鹿空间】c++实现了一个简单的链表数据结构 MyList,其中包含基本的 Get 和 Modify 操作,
数据结构·c++·链表
无尽的大道3 小时前
Java 泛型详解:参数化类型的强大之处
java·开发语言
ZIM学编程3 小时前
Java基础Day-Sixteen
java·开发语言·windows
放逐者-保持本心,方可放逐3 小时前
react 组件应用
开发语言·前端·javascript·react.js·前端框架
UestcXiye3 小时前
《TCP/IP网络编程》学习笔记 | Chapter 9:套接字的多种可选项
c++·计算机网络·ip·tcp
一丝晨光4 小时前
编译器、IDE对C/C++新标准的支持
c语言·开发语言·c++·ide·msvc·visual studio·gcc
阮少年、4 小时前
java后台生成模拟聊天截图并返回给前端
java·开发语言·前端
代码小鑫4 小时前
A027-基于Spring Boot的农事管理系统
java·开发语言·数据库·spring boot·后端·毕业设计
丶Darling.4 小时前
Day40 | 动态规划 :完全背包应用 组合总和IV(类比爬楼梯)
c++·算法·动态规划·记忆化搜索·回溯