设计模式12——中介者模式
中介者模式中,个体与个体之间不需要发生直接关联,而是只需要与中介者进行交互,并由中介完成一系列任务。
Mediator.h内容
1 #ifndef Mediator_H_H 2 #define Mediator_H_H 3 4 #include <iostream> 5 using namespace std; 6 7 class Student; 8 9 class Mediator 10 { 11 public: 12 Mediator() : src(NULL), target(NULL) {} 13 void send(string strMessage); 14 void setTarget(Student *target0) { target = target0; } 15 16 private: 17 Student *src, *target; 18 }; 19 20 class Student 21 { 22 public: 23 Student() : mediator(NULL) {} 24 virtual void recvMessage(string strMessage) = 0; 25 virtual ~Student() {} 26 void sendMessage(Student *student, string strMessage){ 27 mediator->setTarget(student); 28 mediator->send(strMessage); 29 } 30 void setMediator(Mediator *mediator0) { mediator = mediator0; } 31 32 protected: 33 Mediator *mediator; 34 35 }; 36 37 class Student1 : public Student 38 { 39 public: 40 virtual void recvMessage(string strMessage){ 41 cout << "Student1 recv: " << strMessage << endl; 42 } 43 }; 44 45 class Student2 : public Student 46 { 47 public: 48 virtual void recvMessage(string strMessage){ 49 cout << "Student2 recv: " << strMessage << endl; 50 } 51 52 }; 53 54 55 void Mediator::send(string strMessage) 56 { 57 target->recvMessage(strMessage); 58 } 59 60 61 void MediatorTest() 62 { 63 Student *student1 = new Student1(); 64 Student *student2 = new Student2(); 65 Mediator *mediator = new Mediator(); 66 student1->setMediator(mediator); 67 student2->setMediator(mediator); 68 69 student1->sendMessage(student2, "How are you?"); 70 student2->sendMessage(student1, "Very well, Thank you!"); 71 72 delete mediator; 73 74 delete student1; 75 delete student2; 76 77 } 78 79 80 #endif
运行结果:
创建两个student,他们通过中介者实现了交互过程。