中介者模式 测试代码添加

master
a7458969 2020-05-21 22:19:14 +08:00
parent 17ada97cf3
commit a4f2da4a13
2 changed files with 63 additions and 14 deletions

View File

@ -39,36 +39,36 @@ private:
ResponsabilityChan *mHead;
ResponsabilityChan *mTail;
};
template<typename T>
class Mediator;
template<typename T>
class MediatorColleague{
public:
MediatorColleague(std::string name,Mediator *p){
mName = name;
mMediater = p;
}
std::string GetName(){
return mName;
};
int SetMediater(Mediator* p){
int SetMediater(Mediator<T>* p){
mMediater = p;
}
virtual int Send(std::string colleage,T* data){
virtual int Send(std::string colleage,T data)=0;
virtual int Recv(std::string colleage,T data)=0;
protected:
std::string mName;
Mediator<T> *mMediater;
MediatorColleague(std::string name,Mediator<T> *p){
mName = name;
mMediater = p;
}
private:
MediatorColleague(){
}
std::string mName;
Mediator *mMediater;
};
template <typename T>
class Mediator{
public:
virtual int Register(MediatorColleague *p){ // 注册
int Register(MediatorColleague<T> *p){ // 注册
if (nullptr == p){
return -1;
}
@ -79,11 +79,15 @@ public:
p->SetMediater(this);
return -1;
}
virtual int Relay(MediatorColleague *p){ //转发
int Relay(std::string colleage,T data){ //转发
if(mColleague.find(colleage) != mColleague.end()){
MediatorColleague<T> *recvcolleage = mColleague.find(colleage)->second;
recvcolleage->Recv("",data);
}
return -1;
}
private:
std::map<std::string,MediatorColleague*> mColleague;
std::map<std::string,MediatorColleague<T>*> mColleague;
};
#endif //GENERAL_ADAPTER_H

View File

@ -36,6 +36,9 @@ private:
}
};
/*
*/
using namespace std;
class Product :public CloneAble<Product>{
public:
@ -62,7 +65,49 @@ private:
int mAttribute1;
char mAttribute2;
};
/*
* mediater test
*/
class HandleData{
public:
std::string data;
};
class Motherboard :public Mediator<HandleData>{
};
class RAM :public MediatorColleague<HandleData>{
public:
RAM(std::string name,Mediator<HandleData> *p) : MediatorColleague(name,p){
}
int Send(std::string colleage,HandleData data){
this->mMediater->Relay(colleage,data);
}
int Recv(std::string colleage,HandleData data){
std::cout<<colleage<<this->mName<<" receive data "<<data.data<<endl;
}
};
class SoundCard :public MediatorColleague<HandleData>{
public:
SoundCard(std::string name,Mediator<HandleData> *p) : MediatorColleague(name,p){
}
int Send(std::string colleage,HandleData data){
this->mMediater->Relay(colleage,data);
}
int Recv(std::string colleage,HandleData data){
std::cout<<colleage<<this->mName<<" receive data "<<data.data<<endl;
}
};
/*
* mediater test end
*/
int main(){
Motherboard mon;
SoundCard soundcard("souncard",&mon);
RAM ram("ram",&mon);
mon.Register((MediatorColleague<HandleData>*) &soundcard);
mon.Register((MediatorColleague<HandleData>*) &ram);
soundcard.Send("ram",HandleData{"ss"});
BridgeTest br(new MP3Player);
BridgeTest br1(new MP4Player);