设计模式:Mediator中介者模式

//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;
}



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值