首页 > 代码库 > 中介者模式之C++实现
中介者模式之C++实现
可以把邮箱想象成师生交流的一个中介者,它需要知道老师和学生的邮箱地址。
学生和老师都需要维护一个邮箱对象,利用它向彼此发消息。
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Mail;
class User;
class Mail
{
public:
virtual void SendMail(string message, User *user) {};
};
class User
{
protected:
Mail *mail;
public:
User(Mail *email)
{
mail = email;
}
};
class Student: public User
{
public:
Student(Mail *email) : User(email){}
void SendMail(string message)
{
mail->SendMail(message, this);
}
void ReceiveMail(string message)
{
cout << "学生收到邮件:" << message << endl;
}
};
class Professor: public User
{
public:
Professor(Mail *email) : User(email){}
void SendMail(string message)
{
mail->SendMail(message, this);
}
void ReceiveMail(string message)
{
cout << "教授收到邮件:" << message << endl;
}
};
class SchoolMail : public Mail
{
private:
Student *student;
Professor *professor;
public:
void SetStudent(Student *stu)
{
student = stu;
}
void SetProfessor(Professor *teacher)
{
professor = teacher;
}
void SendMail(string message, User *user)
{
if (user == professor)
{
student->ReceiveMail(message);
}
else if (user == student)
{
professor->ReceiveMail(message);
}
}
};
int main(void)
{
SchoolMail *mail = new SchoolMail;
Student *student = new Student(mail);
Professor *professor = new Professor(mail);
mail->SetProfessor(professor);
mail->SetStudent(student);
professor->SendMail("请以XX为题写一篇论文");
student->SendMail("好的,我现在开始准备论文材料");
return 0;
#include <iostream>
#include <string>
using namespace std;
class Mail;
class User;
class Mail
{
public:
virtual void SendMail(string message, User *user) {};
};
class User
{
protected:
Mail *mail;
public:
User(Mail *email)
{
mail = email;
}
};
class Student: public User
{
public:
Student(Mail *email) : User(email){}
void SendMail(string message)
{
mail->SendMail(message, this);
}
void ReceiveMail(string message)
{
cout << "学生收到邮件:" << message << endl;
}
};
class Professor: public User
{
public:
Professor(Mail *email) : User(email){}
void SendMail(string message)
{
mail->SendMail(message, this);
}
void ReceiveMail(string message)
{
cout << "教授收到邮件:" << message << endl;
}
};
class SchoolMail : public Mail
{
private:
Student *student;
Professor *professor;
public:
void SetStudent(Student *stu)
{
student = stu;
}
void SetProfessor(Professor *teacher)
{
professor = teacher;
}
void SendMail(string message, User *user)
{
if (user == professor)
{
student->ReceiveMail(message);
}
else if (user == student)
{
professor->ReceiveMail(message);
}
}
};
int main(void)
{
SchoolMail *mail = new SchoolMail;
Student *student = new Student(mail);
Professor *professor = new Professor(mail);
mail->SetProfessor(professor);
mail->SetStudent(student);
professor->SendMail("请以XX为题写一篇论文");
student->SendMail("好的,我现在开始准备论文材料");
return 0;
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。