就是设计一个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; }
运行:
Mediator Design Pattern 中介者模式,布布扣,bubuko.com
原文地址:http://blog.csdn.net/kenden23/article/details/37755593