using System; using System.Collections.Generic; using System.Text; ///Mediator(中介者)模式 用一个中介对象来封装一系列的对象之间的交互,中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。 ///add by jzh 2007-04-30 namespace DesignPattern { /// <summary> /// 抽象中介者(Mediator)角色:抽象中介者角色定义统一的接口用于各同事角色之间的通信。 /// 具体中介者(Concrete Mediator)角色:具体中介者角色通过协调各同事角色实现协作行为。 /// 为此它要知道并引用各个同事角色。 /// </summary> class Mediator { private DataProviderColleague dataProvider; private DataConsumerColleague dataConsumer; public void IntroduceColleagues(DataProviderColleague c1, DataConsumerColleague c2) { dataProvider = c1; dataConsumer = c2; } public void DataChanged() { int i = dataProvider.MyData; dataConsumer.NewValue(i); } } /// <summary> /// 同事(Colleague)角色:每一个同事角色都知道对应的具体中介者角色, /// 而且与其他的同事角色通信的时候,一定要通过中介者角色协作。 /// 资料应用方(同事A) /// </summary> class DataConsumerColleague { public void NewValue(int i) { Console.WriteLine("New value {0}", i); } } /// <summary> /// 资料提供方(同事B) /// </summary> class DataProviderColleague { private Mediator mediator; private int iMyData = 0; public int MyData { get { return iMyData; } set { iMyData = value; } } public DataProviderColleague(Mediator m) { mediator = m; } public void ChangeData() { iMyData = 8080; // Inform mediator that I have changed the data if (mediator != null) mediator.DataChanged(); } } public class Client { public static void Main(string[] args) { Mediator m = new Mediator(); DataProviderColleague c1 = new DataProviderColleague(m); DataConsumerColleague c2 = new DataConsumerColleague(); m.IntroduceColleagues(c1, c2); c1.ChangeData(); Console.ReadLine(); } } }