您的位置:首页 > 编程语言 > C语言/C++

中介者模式-C++实现

2016-07-18 22:09 369 查看
跟我在公司搭的框架好像。。

// MediatorPattern.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>

using namespace std;

class Student
{
private:
string m_strName;
string m_content;

public:
Student(string strName):m_strName(strName){}
void set_name(string name)
{
m_strName = name;
}

void set_content(string content)
{
m_content = content;
}

string get_name()
{
return m_strName;
}

string get_content()
{
if (m_content.empty())
return "Copy that";
else
return m_content;
}

virtual void talk() = 0;

};

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

};

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

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

class Mediator
{
public:
vector<Student*> vec_student;
void addstu(Student* stu)
{
vec_student.push_back(stu);
}
virtual void notify(Student* stu) {};

};

class QQMediator :public Mediator
{
public:
virtual void notify(Student* stu)
{
stu->talk();
for (int i = 0; i < vec_student.size(); ++i)
{
if (stu != vec_student[i])
{
vec_student[i]->talk();
}
}
}
};
int main()
{
QQMediator qq;
Monitor* mon = new Monitor("mon");
Secretary *sec = new Secretary("sec");
StudentA *stu = new StudentA("stu");

qq.addstu(mon);
qq.addstu(sec);
qq.addstu(stu);

mon->set_content("明天放假");
qq.notify(mon);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: