标签:
//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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/48064285