Mediator(中介者)

18. Mediator(中介者)

18.1 定义

  用一个中介对象封装一系列对象(同事)的交互,中介者使各对象不需要显式地相互作用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

18.2 优点

  ■ 减少类间的依赖,将原有的一对多的依赖变成一对一的依赖,使得对象之间的关系更易维护和理解。

  ■ 避免同事对象之间过度耦合,同事类只依赖于中介者,使同事类更易被复用,中介类和同事类可以相对独立地演化。

  ■ 中介者模式将对象的行为和协作抽象化,将对象在小尺度的行为上与其他对象的相互作用分开处理。

18.3 缺点

  ■ 中介者模式降低了同事对象的复杂性,但增加了中介者类的复杂性。

  ■ 中介者类经常充满了各个具体同事类的关系协调代码,这种代码是不能复用的。

18.4 c++源码实例

  1 #include <iostream>
  2 #include <string>
  3 using namespace std;
  4 
  5 class HousePerson;
  6 class BuyHousePerson;
  7 class SellHousePerson;
  8 
  9 //抽象中介类
 10 class Mediator{
 11 public:
 12     virtual void sendMessage(string msg, HousePerson *p) = 0;
 13 };
 14 
 15 //抽象炒房客
 16 class HousePerson{
 17 public:
 18     HousePerson(Mediator *mediator)
 19     {
 20         m_mediator = mediator;
 21     }
 22 protected:
 23     Mediator *m_mediator;
 24 };
 25 
 26 //买房的人
 27 class BuyHousePerson :public HousePerson
 28 {
 29 public:
 30     BuyHousePerson(Mediator *mediator) :HousePerson(mediator){}
 31     void sendMsg(string msg)
 32     {
 33         m_mediator->sendMessage(msg,this);
 34     }
 35     void notify(string msg)
 36     {
 37         cout << "买房者得到消息:" << msg << endl;
 38     }
 39 };
 40 
 41 //卖房的人
 42 class SellHousePerson :public HousePerson
 43 {
 44 public:
 45     SellHousePerson(Mediator *mediator) :HousePerson(mediator){}
 46     void sendMsg(string msg)
 47     {
 48         m_mediator->sendMessage(msg, this);
 49     }
 50     void notify(string msg)
 51     {
 52         cout << "卖-房者得到消息:" << msg << endl;
 53     }
 54 };
 55 
 56 //具体中介类
 57 class ConcreteMediator :public Mediator
 58 {
 59 public:
 60     void sendMessage(string msg, HousePerson *p)
 61     {
 62         if (p == bh)
 63         {
 64             sh->notify(msg);
 65         }
 66         else
 67         {
 68             bh->notify(msg);
 69         }
 70     }
 71 
 72 public:
 73     BuyHousePerson *bh;
 74     SellHousePerson *sh;
 75 };
 76 
 77 //客户端
 78 int main()
 79 {
 80     ConcreteMediator *pM = new ConcreteMediator;
 81     BuyHousePerson *pBh = new BuyHousePerson(pM);
 82     SellHousePerson* pSh = new SellHousePerson(pM);
 83 
 84     pM->bh = pBh;
 85     pM->sh = pSh;
 86 
 87     pBh->sendMsg("卖不卖,一口价780W");
 88     pSh->sendMsg("不卖,至少800W!");
 89 
 90     if (pM)
 91     {
 92         delete pM;
 93         pM = nullptr;
 94     }
 95     if (pBh)
 96     {
 97         delete pBh;
 98         pBh = nullptr;
 99     }
100     if (pSh)
101     {
102         delete pSh;
103         pSh = nullptr;
104     }
105 
106     return 0;
107 }

 

posted @ 2020-11-08 14:08  昨日明眸  阅读(372)  评论(0)    收藏  举报