欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > asp.net >内容正文

asp.net

设计模式复习-中介者模式

发布时间:2025/6/17 asp.net 39 豆豆
生活随笔 收集整理的这篇文章主要介绍了 设计模式复习-中介者模式 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

#pragma once #include "stdafx.h" #include<map> #include<set> #include<string> #include<iostream> using namespace std;/*设计模式-中介者模式(Mediator)用一个中介对象来封装一系列的对象交互。中介者使各个对象不需要 显示地相互引用,从而使其耦合松散,而且可以独立地改变他们之间的交互。 中介者模式的有点来自集中控制,其缺点也是他,中介者模式一般应用于一组对象 定义良好但是复杂的方式进行通讯的场合,以及想定制一个分布式在多个类中的行为, 而又不想生成太多的子类的场合。 */class CMediator {//抽象中介者 public:virtual void Send(const string &strPeople, const string &strMessage) = 0; };class CColleague {//抽象同事类 protected:CMediator *mpMediator; public:CColleague(CMediator *pMediator) {mpMediator = pMediator;}virtual void Notify(const string &strMessage) = 0; };class CConcreteColleague1 :public CColleague {//同事类1 public:CConcreteColleague1(CMediator *pMediator) :CColleague(pMediator) {}void Send(const string &strPeople, const string &strMessage) {mpMediator->Send(strPeople , strMessage);}void Notify(const string &strMessage) {cout << "tong shi 1 de dao xin xi:" << strMessage << endl;} };class CConcreteColleague2 :public CColleague {//同事类2 public:CConcreteColleague2(CMediator *pMediator) :CColleague(pMediator) {}void Send(const string &strPeople, const string &strMessage) {mpMediator->Send(strPeople, strMessage);}void Notify(const string &strMessage) {cout << "tong shi 2 de dao xin xi:" << strMessage << endl;} };class CConcreteMediator :public CMediator {//具体中介者类 private:map<string, CColleague*>mpColleague; public:CConcreteMediator() {mpColleague.clear();}void Send(const string &strPeople, const string &strMessage) {mpColleague[strPeople]->Notify(strMessage);}void AddColleague(const string &strPeople ,CColleague * pColleague) {mpColleague[strPeople] = pColleague;} };int main() {CConcreteMediator *pM = new CConcreteMediator();CConcreteColleague1 *pC1 = new CConcreteColleague1(pM);CConcreteColleague2 *pC2 = new CConcreteColleague2(pM);pM->AddColleague("pC1", pC1);pM->AddColleague("pC2", pC2);pC1->Send("pC2","chi fan mei?");pC2->Send("pC1", "mei ne");delete pM, delete pC1, delete pC2;getchar();return 0; }

 

总结

以上是生活随笔为你收集整理的设计模式复习-中介者模式的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。