Mediator (C++实现)

好文章推荐: http://blog.csdn.net/roynee/archive/2009/10/05/4634197.aspx

 

下面是简单实现:(转载)

class Mediator;


class Colleage
{
public:
virtual ~Colleage(){};
virtual void Action()=0;
virtual void SetState(const string& sd)=0;
virtual string GetState()=0;
protected:
Colleage(){};
Colleage(Mediator* mdt){this->m_mdt=mdt;};
Mediator* m_mdt;
};

class ConcreteColleageA:public Colleage
{
public:
ConcreteColleageA(){};
ConcreteColleageA(Mediator* mdt):Colleage(mdt){}
~ConcreteColleageA(){};
void SetState(const string& sd){m_sd=sd;}
string GetState(){return m_sd;}
void Action();
private:
string m_sd;
};
class ConcreteColleageB:public Colleage
{
public:
ConcreteColleageB(){};
ConcreteColleageB(Mediator* mdt):Colleage(mdt){}
~ConcreteColleageB(){};
void SetState(const string& sd){m_sd=sd;};
string GetState(){return m_sd;}
void Action();
private:
string m_sd;
};
class Mediator
{
public:
virtual ~Mediator(){};
virtual void DoActionFromAtoB()=0;
virtual void DoActionFromBtoA()=0;
protected:
Mediator(){};
};
class ConcreteMediator:public Mediator
{
public:
ConcreteMediator(){};
ConcreteMediator(Colleage* ClA,Colleage* ClB){m_ClA=ClA;m_ClB=ClB;};
~ConcreteMediator(){};
void SetConA(Colleage* ClA){m_ClA=ClA;}
void SetConB(Colleage* ClB){m_ClB=ClB;}
Colleage* GetConA(){return m_ClA;}
Colleage* GetConB(){return m_ClB;}
void DoActionFromAtoB(){m_ClB->SetState(m_ClA->GetState());}
void DoActionFromBtoA(){m_ClA->SetState(m_ClB->GetState());}
void IntroColleage(Colleage* ClA,Colleage* ClB)
{
m_ClA=ClA;m_ClB=ClB;
}
private:
Colleage* m_ClA;
Colleage* m_ClB
;
};

void ConcreteColleageA::Action()
{
m_mdt->DoActionFromAtoB();
cout<<"CONB "<<this->GetState()<<endl;
}
void ConcreteColleageB::Action()
{
m_mdt->DoActionFromBtoA();
cout<<"CONA "<<this->GetState()<<endl;
}
void main()
{
ConcreteMediator* m=new ConcreteMediator();
ConcreteColleageA* c1=new ConcreteColleageA(m);
ConcreteColleageB* c2=new ConcreteColleageB(m);
m->IntroColleage(c1,c2);
c1->SetState("jackill");
c1->Action();
c2->SetState("rukawa");
c2->Action();
cout<<endl;
c1->SetState("new");
c1->Action();
c2->Action();
cout<<endl;
}

你可能感兴趣的:(media)