就是设计一个Mediator类,能够处理其它类的关系。
Mediator类:
1 拥有其它全部类的实例对象
2 设置一个接口供其它类使用,其它类也拥有一个Mediator类成员,仅仅需调用这个Mediator接口函数使用,无需自己处理关系。
3 Mediator内部已经设置好各个类的关系了,其它类仅仅要直接使用Mediator处理关系就能够了。
以下是一个聊天室聊天是处理关系的实例程序:
进入聊天室的人仅仅须要选定和谁聊天就能够了,无需操心这些信息是怎样传递的,这个已经由Mediator自己主动处理了。
不能对未进入聊天室的人聊天。
能够看出这种代码还是十分简洁清晰的,假设不使用这个模式,那么会臃肿非常多。并且每次send都要写很多其它额外的代码。
使用Mediator设计模式之后,每次仅仅须要send就能够发送信息到须要的人了。
#include <stdio.h>
#include <vector>
#include <string>
using std::string;
using std::vector;
class RoomMember;
class Mediator
{
protected:
vector<RoomMember *> rms;
public:
virtual void enterRoom(RoomMember *mem)
{
rms.push_back(mem);
}
virtual void send(string mes, RoomMember *rm) = 0;
};
class RoomMember
{
protected:
Mediator *mediator;
public:
string name;
RoomMember(Mediator *m, string n) : mediator(m), name(n) {}
virtual void send(string mes, RoomMember *to)
{
printf("%s send a message.\n", name.c_str());
mediator->send(mes, to);
}
virtual void notify(string mes)
{
printf("%s got a message: %s\n", name.c_str(), mes.c_str());
}
};
class MessageMediator : public Mediator
{
public:
void send(string mes, RoomMember *mem)
{
auto it = rms.begin();
for ( ; it != rms.end(); it++)
{
if (*it == mem) break;
}
if (it == rms.end()) //不能是*it != mem。由于it == rms.end()为空指针
{
printf("Not member %s in the room\n", mem->name.c_str());
return ;
}
mem->notify(mes);
}
};
int main()
{
Mediator *mediator = new MessageMediator;
RoomMember *Jelly = new RoomMember(mediator, "Jelly");
RoomMember *Kelly = new RoomMember(mediator, "Kelly");
RoomMember *Billy = new RoomMember(mediator, "Billy");
RoomMember *Silly = new RoomMember(mediator, "Silly");
mediator->enterRoom(Jelly);
mediator->enterRoom(Kelly);
mediator->enterRoom(Billy);
Jelly->send("How are you?", Kelly);
Kelly->send("Never better.", Jelly);
Jelly->send("Where are you?", Billy);
Kelly->send("What are you doing?", Silly);
delete Silly;
delete Kelly;
delete Billy;
delete Jelly;
delete mediator;
return 0;
}
执行: