c++ 中介者模式

本文介绍了一种使用C++实现的中介者模式,通过一个QQ群聊天的例子展示了如何利用该模式来组织多个对象间的交互。主要实现了基本的Colleage类及派生的Monitor、Secretary、StudentA和StudentB等角色类,并通过Mediator类协调这些角色之间的通信。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Colleage
{
private:
string name;
string content;
public:
Colleage(string n = " "):name(n){};
void set_name(string name)
{
this->name = name;
}
string get_name()
{
return this->name;
}
void set_content(string content)
{
this->content = content;
}
string get_content()
{
if(content.size() != 0)
return content;
else return "Copy that";
}
virtual void talk(){};

};

class Monitor : public Colleage
{
public:
Monitor(string n = ""):Colleage(n){};
virtual void talk()
{
cout<<"班长 "<<get_name()<<" 说:"<<get_content()<<endl;
}
};

class Secretary : public Colleage
{
public:
Secretary(string n = ""):Colleage(n){};
virtual void talk()
{
cout<<"团支书 "<<get_name()<<" 说:"<<get_content()<<endl;
}
};

class StudentA : public Colleage
{
public:
StudentA(string n = ""):Colleage(n){};
virtual void talk()
{
cout<<"学生 A "<<get_name()<<" 说:"<<get_content()<<endl;
}
};

class StudentB : public Colleage
{
public:
StudentB(string n = ""):Colleage(n){};
virtual void talk()
{
cout<<"学生 B "<<get_name()<<" 说:"<<get_content()<<endl;
}
};

class Mediator
{
public:
vector<Colleage*> studentList;
virtual void add_student(Colleage *student)
{
studentList.push_back(student);
};
virtual void notify(Colleage *student){};
};

class QQMediator : public Mediator
{
public:
virtual void notify(Colleage *student)
{
student->talk();
for(int i = 0 ; i < studentList.size() ; ++i)
{
if(student != studentList[i])
{
studentList[i]->talk();
}
}
};
};


int main()
{
QQMediator qq;
Monitor *studentMonitor = new Monitor("Foxx");
Secretary *studentSecretary = new Secretary("TC");
StudentA *studentA = new StudentA("Jack");
StudentB *studentB = new StudentB("Frank");

qq.add_student(studentSecretary);
qq.add_student(studentA);
qq.add_student(studentB);

studentMonitor->set_content("明天开始放假!");
qq.notify(studentMonitor);

system("pause");
return 0;
}

c++ 中介者模式 - 1307520486 - 1307520486的博客 转发至微博
c++ 中介者模式 - 1307520486 - 1307520486的博客 转发至微博
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值