码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式:Mediator中介者模式

时间:2015-08-28 23:18:30      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:

//main.h

#pragma once
class Mediator;
class School
{
public:
	virtual void action()=0;
	virtual void Setname(const char *buff)=0;
protected:
	Mediator *mt;
	char namebuff[10];
};
class Studentone : public School
{
public:
	Studentone(Mediator *_mt, const char *name);
	void action();
	void Setname(const char *buff);
	char *Getname();
};
class Studenttwe : public School
{
public:
	Studenttwe(Mediator *_mt, const char *name);
	void action();
	void Setname(const char *buff);
	char *Getname();
};

class Mediator
{
public:
	void StartInit(Studentone *_one, Studenttwe *twe);
	void SetstatusBtoA();
	void SetstatusAtoB();
	void Printf();
private:
	Studentone *one;
	Studenttwe *twe;
};

//main.cpp

#include <iostream>
#include <string.h>
using namespace std;

#include "main.h"
#include <iostream>
using namespace std;
Studentone::Studentone(Mediator *_mt,const char *name)
{
	mt = _mt;
	strcpy(namebuff,name);
}
void Studentone::action()
{
	mt->SetstatusAtoB();//A状态切换到B状态。
}
void Studentone::Setname(const char *buff)
{
	strcpy(namebuff,buff);
}
char * Studentone::Getname()
{
	return namebuff;
}
///////////////////////////////////////////
Studenttwe::Studenttwe(Mediator *_mt,const char *name)
{
	mt = _mt;
	strcpy(namebuff,name);
}
void Studenttwe::action()
{
	mt->SetstatusBtoA();//B状态切换到A状态,内部子类的切换。
}
void Studenttwe::Setname(const char *buff)
{
	strcpy(namebuff, buff);
}
char * Studenttwe::Getname()
{
	return namebuff;
}

/////////////////////////////////////
void Mediator::StartInit(Studentone *_one, Studenttwe *_twe)
{
	one = _one;
	twe = _twe;
}
void Mediator::SetstatusBtoA()
{
	one->Setname(twe->Getname());
}
void Mediator::SetstatusAtoB()
{
	twe->Setname(one->Getname());
}
void Mediator :: Printf()
{
	cout << "Studentone::" << one->Getname() << endl;
	cout << "Studenttwe::" << twe->Getname() << endl;
}

int main()
{
	Mediator *mt = new Mediator();
	Studentone *one = new Studentone(mt,"123");
	Studenttwe *twe = new Studenttwe(mt,"123");

	mt->StartInit(one,twe);
	mt->Printf();

	one->Setname("456");
	one->action();//one通知twe。
	mt->Printf();

	twe->Setname("789");
	twe->action();//twe通知one;
	mt->Printf();
	//中介者模式就是为类与类的内部交流建立一座桥梁。
	return 0;
}
技术分享


版权声明:本文为博主原创文章,未经博主允许不得转载。

设计模式:Mediator中介者模式

标签:

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/48064285

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!