大胖的部落格

Just a note

  C++博客 :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  112 随笔 :: 0 文章 :: 3 评论 :: 0 Trackbacks
用一个中介对象Mediator来封装其它对象之间的交互,每个其它类型的对象只与Mediator交互。
每个其它类型对象都包含有同一个Mediator指针,Mediator中包含有所有其他类型对象指针。
每个其它类型对象调用Mediator接口,由Mediator对其它对象进行操作。

#include <iostream>

using namespace std;

class Mediator;

//colleague基类,每个colleague都保存一个Mediator,colleague只与Mediator有交互
class Colleague
{
public:
    Colleague(
int i, Mediator* p):value(i), pm(p){}
    
virtual ~Colleague(){}
    
virtual void CopyMineToAnother() = 0;
    
int GetValue() const {return value;}
    
void SetValue(int i) {value = i;}
protected:
    Mediator
* pm;
private:
    
//用来区分colleague
    int value;
}
;

class ColleagueA: public Colleague
{
public:
    ColleagueA(Mediator
* p, int i):Colleague(i,p){} 
    
void CopyMineToAnother();
}
;

class ColleagueB: public Colleague
{
public:
    ColleagueB(Mediator
* p, int i):Colleague(i,p){} 
    
void CopyMineToAnother();
}
;

//Mediator
class Mediator
{
public:
    
//传入colleague的接口
    void SetColleague(Colleague* a, Colleague* b)
    
{
        pa 
= a;
        pb 
= b;
    }

    
//协作colleague的接口
    void AtoB()
    
{
        
int i = pa->GetValue();
        pb
->SetValue(i);
    }

    
void BtoA()
    
{
        
int i = pb->GetValue();
        pa
->SetValue(i);
    }

private:
    Colleague
* pa;
    Colleague
* pb;
}
;

void ColleagueA::CopyMineToAnother()
{
    
//colleague内部只与Mediator交互
    pm->AtoB();
}

void ColleagueB::CopyMineToAnother()
{
    
//colleague内部只与Mediator交互
    pm->BtoA();
}


int main()
{
    Mediator
* pm = new Mediator;
    Colleague
* pa = new ColleagueA(pm, 2);
    Colleague
* pb = new ColleagueB(pm, 5);

    
//设置Mediator中的colleague
    pm->SetColleague(pa,pb);
    
//获得a和b的值
    cout<<pa->GetValue()<<endl;
    cout
<<pb->GetValue()<<endl;
    
//调用CopyMineToAnother,在其内部只与Mediator交互
    pa->CopyMineToAnother();
    
//b的值被改变
    cout<<pb->GetValue()<<endl;
    
    delete pa;
    delete pb;
    delete pm;
    
return 0;
}
posted on 2009-06-10 11:48 大胖 阅读(164) 评论(0)  编辑 收藏 引用 所属分类: Design Pattern

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理