结构行为型设计模式之中介者模式(Mediator)-LMLPHP
意图用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
适用性
  • 一组对象以定义良好但是复杂的方式进行通信。产生的相互依赖关系结构混乱且难以理解。
  • 一个对象引用其他很多对象并且直接与这些对象通信,导致难以复用该对象。
  • 想定制一个分布在多个类中的行为,而又不想生成太多的子类。
 using System;

     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);
}
} class DataConsumerColleague
{
public void NewValue(int i)
{
Console.WriteLine("New value {0}", i);
}
} class DataProviderColleague
{
private Mediator mediator;
private int iMyData=;
public int MyData
{
get
{
return iMyData;
}
set
{
iMyData = value;
}
}
public DataProviderColleague(Mediator m)
{
mediator = m;
} public void ChangeData()
{
iMyData = ; // Inform mediator that I have changed the data
if (mediator != null)
mediator.DataChanged();
}
} /// <summary>
/// Summary description for Client.
/// </summary>
public class Client
{
public static int Main(string[] args)
{
Mediator m = new Mediator();
DataProviderColleague c1 = new DataProviderColleague(m);
DataConsumerColleague c2 = new DataConsumerColleague();
m.IntroduceColleagues(c1,c2); c1.ChangeData(); return ;
}
}

中介者模式

05-11 22:38