设计模式---中介者模式

来源:互联网 发布:2016真正的人工智能股 编辑:程序博客网 时间:2024/05/24 04:51
尽管将一个系统分割成许多对象通常可以增加其复用性,但是对象间相互连接的激增又会降低其可复用性了。
大量的连接使得一个对象不可能在没有其他对象的支持下工作,系统表现为一个不可分割的整体,所以,对系统的行为进行任何较大的改动就十分困难了。

中介者模式
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

中介者模式容易在系统中应用,也很容易在系统中误用。当系统出现了‘多对多’交互复杂的对象群时,不要急于使用中介者模式,而要先反思你的系统在设计上是不是合理。

中介者模式一般用于一组对象以定义良好但是复杂的方式进行通信的场合,以及想定制一个分布在多个类中的行为,而又不想生成太多子类的场合。


#include<iostream>

using namespace std;

class Country;
class UnitedNations
{
    public:
        virtual    void Declare(string message,Country *colleague){}
};


class Country
{
    protected:
        UnitedNations *mediator;
    public:
        Country(UnitedNations *mediator)
        {
            this->mediator = mediator;
        }
        virtual void GetMessage(string mes){}
};

class USA:public Country
{
    public:
        USA(UnitedNations *mediator):Country(mediator){}
        void CountryDeclare(string message)
        {
            mediator->Declare(message,this);
        }
        void GetMessage(string mes)
        {
            cout<<"i am usa : "<<mes<<endl;
        }
};

class Iraq:public Country
{
    public:
        Iraq(UnitedNations *mediator):Country(mediator){}
        void CountryDeclare(string message)
        {
            mediator->Declare(message,this);
        }
        void GetMessage(string mes)
        {
            cout<<"i am Iraq : "<<mes<<endl;
        }
};

class UnitedNationsSecurityCouncil: public UnitedNations
{
    private:
        Country *coll1;
        Country *coll2;
    public:
        void SetUSA(Country *col)
        {
            coll1 = col;
        }
        void SetIraq(Country *col)
        {
            coll2 = col;
        }
        void Declare(string mess,Country *coll)
        {
            if(coll == coll1)
            {
                coll2->GetMessage(mess);
            }
            else if (coll == coll2)
            {
                coll1->GetMessage(mess);
            }
        }
};

int main()
{
    UnitedNationsSecurityCouncil *UNSC = new UnitedNationsSecurityCouncil();

    USA *usa = new USA(UNSC);
    Iraq *is = new Iraq(UNSC);

    UNSC->SetUSA(usa);
    UNSC->SetIraq(is);

    usa->CountryDeclare("from usa iraq can not do it");
    is->CountryDeclare("from iraq i can do that");

    return 0;
}