设计模式17 - 中介者模式

作者:billy
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处

中介者模式

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

使用场景

  • 系统中对象之间存在比较复杂的引用关系,导致它们之间的依赖关系结构混乱而且难以复用该对象。
  • 想通过一个中间类来封装多个类中的行为,而又不想生成太多的子类。

优缺点

  • 优点:
    1、降低了类的复杂度,将一对多转化成了一对一。
    2、各个类之间的解耦。
    3、符合迪米特原则。

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

注意事项

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

UML结构图

在这里插入图片描述

代码实现

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 ] : !
发布了61 篇原创文章 · 获赞 218 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_34139994/article/details/95641228