📄 c20-中介者模式例.txt
字号:
//中介者
//原始设计
//.h文件
class Wife;
class Husband
{
public:
Husband(int nage):age(nage) {}
int Age() const {return age;}
void SetWife(Wife * wife) {w=wife;}
int GetWifeAge() const;
private:
int age;
Wife * w;
};
class Wife
{
public:
Wife(int nage):age(nage) {}
int Age() const {return age;}
void SetHusband(Husband * husband){h=husband;}
int GetHusbandAge() const;
private:
int age;
Husband * h;
};
//.cpp文件
int Husband::GetWifeAge() const {return w->Age();}
int Wife::GetHusbandAge() const {return h->Age();}
void main()
{
//创建对象
Husband h(30);
Wife w(28);
h.SetWife(&w);
w.SetHusband(&h);
//应用
cout<<h.GetWifeAge()<<endl;
cout<<w.GetHusbandAge()<<endl;
}
//-------------------------------------------------------------------------
//采用中介者模式
//.h文件
class Couple;
class Husband
{
public:
Husband(int nage):age(nage) {}
int Age() const {return age;}
//void (Wife * wife) {w=wife;}
void SetCouple(Couple * p){couple=p;}
int GetWifeAge() const;// {return couple->GetWifeAge();}
private:
int age;
Couple * couple;
};
class Wife
{
public:
Wife(int nage):age(nage) {}
int Age() const {return age;}
//void SetHusband(Husband * husband){h=husband;}
void SetCouple(Couple * p){couple=p;}
int GetHusbandAge() const;
private:
int age;
Couple * couple;
};
class Couple
{
public:
Couple(Husband * husband,Wife * wife)
:h(husband),w(wife) {husband->SetCouple(this);wife->SetCouple(this);}
int GetHusbandAge() const {return h->Age();}
int GetWifeAge() const {return w->Age();}
private:
Husband * h;
Wife * w;
};
//.cpp文件
int Husband::GetWifeAge() const {return couple->GetWifeAge();}
int Wife::GetHusbandAge() const {return couple->GetHusbandAge();}
void main()
{
Husband h(30);
Wife w(28);
Couple couple(&h,&w);
//应用
cout<<h.GetWifeAge()<<endl;
cout<<w.GetHusbandAge()<<endl;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -