吾爱破解 - 52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 942|回复: 0
收起左侧

[讨论] 中介者模式

[复制链接]
古月不傲 发表于 2020-11-16 18:51
[C++] 纯文本查看 复制代码
#include <iostream>

using namespace std;

namespace mediator_pattern {

class abstract_person;

// 抽象中介
class abstract_mediator {
public:
    virtual void set_obj1(abstract_person *person) = 0;
    virtual void set_obj2(abstract_person *person) = 0;
    virtual void send_msg(abstract_person *person, string msg) = 0;
    virtual ~abstract_mediator() {}
};

// 抽象人
class abstract_person {
public:
    virtual void set_mediator(abstract_mediator *mediator) = 0;
    virtual void send(string msg) = 0;
    virtual void get(string msg) = 0;
    virtual ~abstract_person() {}
protected:
    abstract_mediator *m_mediator;
};

// 男人
class man : public abstract_person {
public:
    virtual void set_mediator(abstract_mediator *mediator) override {
        this->m_mediator = mediator;
    }
    virtual void send(string msg) override {
        this->m_mediator->send_msg(this, msg);
    }
    virtual void get(string msg) override {
        printf("收到信息:%s\n", msg.c_str());
    }
};

// 女人
class woman : public abstract_person {
public:
    virtual void set_mediator(abstract_mediator *mediator) override {
        this->m_mediator = mediator;
    }
    virtual void send(string msg) override {
        this->m_mediator->send_msg(this, msg);
    }
    virtual void get(string msg) override {
        printf("收到信息:%s\n", msg.c_str());
    }
};

// qq 辅助类 
class qq : public abstract_mediator {
public:
    qq() : m_one{}, m_two{} {}
    virtual void set_obj1(abstract_person *person) override {
        this->m_one = person; 
    }
    virtual void set_obj2(abstract_person *person) override {
        this->m_two = person; 
    }
    void send_msg(abstract_person *person, string msg) override {
        if (person == this->m_one)
            this->m_one->get(msg);
        else if (person == this->m_two)
            this->m_two->get(msg);
        else
            return;
    }
    abstract_person *m_one;
    abstract_person *m_two;
};
}

// 可以看出通过中介者模式 可以有效的解耦类与类之间的相互引用
int main(void)
{
    using namespace mediator_pattern;

    abstract_person *m = new man;
    abstract_person *wm = new woman;

    abstract_mediator *q = new qq;

    q->set_obj1(m);
    q->set_obj2(wm);

    m->set_mediator(q);
    wm->set_mediator(q);
    m->send("爱你,宝贝");
    wm->send("我也爱你宝贝");

    delete q;
    delete wm;
    delete m;

    return 0;
}

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
Willion + 1 + 1 谢谢@Thanks!

查看全部评分

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则

返回列表

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-11-26 11:32

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表