C++设计模式:中介者模式

中介者模式

中介者模式(Mediator Pattern)是用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。中介者模式属于行为型模式。

使用场景

系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象。

想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。

优缺点

优点:

1、降低了类的复杂度,将一对多转化成了一对一。

2、各个类之间的解耦。

3、符合迪米特原则。

缺点:

中介者会庞大,变得复杂难以维护。

注意事项

不应当在职责混乱的时候使用。

UML结构图

扫描二维码关注公众号,回复: 14714842 查看本文章

代码实现

chatroom.h
创建中介类 - 聊天室,负责传送通信

#include <string>
#include <ctime>
#include <iostream>
using namespace std;

class ChatRoom
{
public:
    void showMessage(string name, string message)
    {
        time_t setTime;
        time(&setTime);
        tm* ptm = localtime(&setTime);
        std::string time = std::to_string(ptm->tm_year + 1900)
                         + "/"
                         + std::to_string(ptm->tm_mon + 1)
                         + "/"
                         + std::to_string(ptm->tm_mday)
                         + " "
                         + std::to_string(ptm->tm_hour) + ":"
                         + std::to_string(ptm->tm_min) + ":"
                         + std::to_string(ptm->tm_sec);

        cout << time + " [ " + name + " ] : " + message << endl;
    }
};

usr.h
创建用户类,在发送消息时使用中介类

#include "chatroom.h"

class User
{
public:
    User(string name) : name(name)
    {
        cout << "init user " + name << endl;
    }

    string getName() { return this->name; }

    void setName(string name) { this->name = name; }

    void showMessage(string message)
    {
        ChatRoom chatRoom;
        chatRoom.showMessage(this->name, message);
    }

private:
    string name;
};

main.cpp
实例应用 - 通过中介者完成了对象之间的通信

#include "user.h"

int main()
{
    User *user1 = new User("Billy");
    User *user2 = new User("Kitty");
    User *user3 = new User("Alice");
    cout << endl;

    user1->showMessage("hello");
    user2->showMessage("world");
    user3->showMessage("!");

    return 0;
}

运行结果:
init user Billy
init user Kitty
init user Alice

2019/7/17 9:54:13 [ Billy ] : hello
2019/7/17 9:54:13 [ Kitty ] : world
2019/7/17 9:54:13 [ Alice ] : !

本文福利,费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击费领取↓↓

猜你喜欢

转载自blog.csdn.net/m0_73443478/article/details/129751377
今日推荐