天天看點

中介者模式(mediator)(C++)

什麼是中介者模式

**中介者模式mediator,**用一個中介對象來封裝一系列的對象互動,中介者對象使各對象不需要顯示的互相引用,進而使其耦合松散,并且可以獨立的改變他們之間的互動方式

角色

角色 角色作用
抽象中介者 包含一個所有col對象,和一個抽象接口
具體中介者 實作具體接口
抽象同僚 包含中介,以及與中介互動的接口
具體同僚 實作接口
中介者模式(mediator)(C++)
#include <string>
#include <iostream>
#include<vector>
#include<initializer_list>
using namespace std;
class Colleague; \\必須前項申明,不然編譯不過

class Mediator \\抽象中介者
{
public:
    virtual void send(std::string  msg, Colleague * p, string receiveName) = 0; \\send函數,用于col之間消息互動,包含消息msg,發送方p,和接收方name
};

class Colleague \\col抽象類
{
protected:
    Mediator * m_mediator; \\每個對象都應該認識中介
    string selfName; \\每個對象名字
public:
    Colleague(Mediator * p, string name)
    {
        m_mediator = p;
        selfName = name;
    }
    virtual void send(std::string msg, string receiveName) = 0;
    virtual void notify(std::string msg, string sendName) = 0;
    const string getSelfName()
    {
        return selfName;
    }
};

class ConcreteColleague : public Colleague
{
public:
    ConcreteColleague(Mediator * p, string name) : Colleague(p, name) {}
    void send(std::string msg, string receiveName)
    {
        m_mediator->send(msg, this, receiveName);
    }
    void notify(std::string msg, string sendName)
    {
        std::cout << sendName << "send" << msg << "to" << this->getSelfName() << std::endl;
    }
};


class ConcreteMediator : public Mediator
{
private:
    vector<Colleague *> collList;
public:
    void addColleague(initializer_list<Colleague *> initList)
    {
        for(auto it : initList)
            collList.push_back(it);
    }
    void send(std::string msg, Colleague * p, string receiveName)
    {
        // 這裡接受來自一個同僚發過來的消息,具體應該給誰要根據需求來
        // 這裡知識一個很簡單的應用。比如該類總可以是有兩個隊列。
        // 一個隊列是客戶,一個隊列是客服
        for(auto it : collList)
        {
            if(receiveName == it->getSelfName())
            {
                it->notify(msg, p->getSelfName());
            }
        }
    }
};

int main()
{
    // 中介者模式
    ConcreteMediator * p = new ConcreteMediator();
    Colleague * pCol1 = new ConcreteColleague(p, "col1");
    Colleague * pCol2 = new ConcreteColleague(p, "col2");
    p->addColleague({pCol1, pCol2});
    pCol1->send("你下班了嗎?", "col2");

    delete pCol1;
    delete pCol2;
    delete p;

    getchar();
    return 0;
}
           

這裡我改變了很多實作,都是自己添加的

https://blog.csdn.net/konglongdanfo1/article/details/83381630

與該部落格中實作有差别,但是具體的意義是一樣的

應用場景

①優點

減少類間依賴,把一對多的依賴轉變成一對一。同僚類隻依賴中介,降低類間耦合

②缺點,中介者會随着同僚類的增多,邏輯越來越複雜

繼續閱讀