4.5 Mediator(中介者)

【返回目录】

一提到“中介”,人们往往常常想到“租房”,是的,现在像我们这样在外地混的游子太多太多了。出来混,迟早是要租房的,租房又免不了跟中介打交道。

通常的流程是:房东想要出租自己的闲置住房,但是对于一些手续上的事情不是太了解,并且也不想什么事情都来折腾自己,索性委托一家中介公司,别人赚点儿就赚点儿吧,自己倒也省事儿了。现在租房的人,不论是在网上还是在电线杆子上看到的招租信息十有八九都是中介发布的,所以租房子也免不了要经过中介。既然两个都愿租,那么中介收了手续费后就会介绍两人认识,然后看房,觉得合适就签协议付房租,没看好中介又会给租户介绍新的房东,给房东介绍新的租户,而房东和租户之间并没有多少牵连。

流程很简单,同样的方式完全可以用于计算机程序设计,利用一个中介对象来封装一套对象交互,中介者使各对象不需要相互显式地引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。

   1: using System;
   2:  
   3: namespace Autumoon.DesignPatterns.Mediator
   4: {
   5:     public class MediatorDemo
   6:     {
   7:         private Landlord currentLandlord = null;
   8:         private Lodger currentLodger = null;
   9:  
  10:         public void IntroduceColleagues(Landlord landlord, Lodger lodger)
  11:         {
  12:             currentLandlord = landlord;
  13:             currentLodger = lodger;
  14:         }
  15:  
  16:         public void PriceChanged()
  17:         {
  18:             currentLodger.ProvidePrice(currentLandlord.Price);
  19:         }
  20:     }
  21:  
  22:     public class Landlord
  23:     {
  24:         private MediatorDemo CurrentMediator { get; set; }
  25:         public int Price { get; set; }
  26:  
  27:         public Landlord(MediatorDemo mediator)
  28:         {
  29:             this.CurrentMediator = mediator;
  30:         }
  31:  
  32:         public void ProvidePrice()
  33:         {
  34:             this.Price = 1800;
  35:  
  36:             if (this.CurrentMediator != null)
  37:             {
  38:                 this.CurrentMediator.PriceChanged();
  39:             }
  40:         }
  41:     }
  42:  
  43:     public class Lodger
  44:     {
  45:         public void ProvidePrice(int price)
  46:         {
  47:             Console.WriteLine("Consumer provides price is " + price + " RMB/Month.");
  48:         }
  49:     }
  50: }

我说了,出来混,迟早是要租房的:

   1: static void Main(string[] args)
   2: {
   3:     #region Mediator
   4:     MediatorDemo mediator = new MediatorDemo();
   5:     Landlord landlord = new Landlord(mediator);
   6:     Lodger lodger = new Lodger();
   7:     mediator.IntroduceColleagues(landlord, lodger);
   8:  
   9:     landlord.ProvidePrice();
  10:     #endregion
  11:  
  12:     Console.ReadLine();
  13: }

Architecture

posted @ 2008-02-22 18:10  麦机长  阅读(718)  评论(2编辑  收藏  举报