中介者模式:
Mediator:用一个中介对象封装一系列的对象交互。中介者使各对象不需要显示的相互引用,从而使其耦合松散,而且可以独立改变他们之间的交互
注意:
一般用于一组对象以定义良好但是复杂的方式进行通信的场合
中介者很容易在系统中应用,也很容易在系统中误用。
当系统出现“多对多“交互复杂的对象群时,不要急于使用中介者模式,而是先反思你的系统在设计上是不是合理。
Demo1:
//抽象中介者类,定义了同事对象到中介者对象的接口
abstract class Mediator
{
//定义一个抽象的发送消息方法,得到同事对象和发送信息
public abstract void Send(string message,Colleague colleague);
}
//具体中介者类
class ConcreteMediator:Mediator
{
private ConcreteColleague1 colleague1;
private ConcreteColleague2 colleague2;
public ConcreteColleague1 Colleague1
{
set { colleague1 = value; }
}
public ConcreteColleague2 Colleague2
{
set { colleague2 = value; }
}
public override void Send(string message, Colleague colleague)
{
if (colleague == colleague1)
{
colleague2.Notify(message);
}
else
{
colleague1.Notify(message );
}
}
}
//抽象同事类
abstract class Colleague
{
protected Mediator mediator;
public Colleague(Mediator mediator)
{
this.mediator = mediator;//构造方法,得到中介者对象
}
}
class ConcreteColleague1:Colleague
{
public ConcreteColleague1(Mediator mediator):base(mediator)
{}
public void Send(string message)
{
//发送消息时通常是中介者发送去的
mediator.Send(message,this);
}
public void Notify(string message)
{
Console.WriteLine("同事1得到消息:"+message);
}
}
class ConcreteColleague2 : Colleague
{
public ConcreteColleague2(Mediator mediator)
: base(mediator)
{ }
public void Send(string message)
{
//发送消息时通常是中介者发送去的
mediator.Send(message, this);
}
public void Notify(string message)
{
Console.WriteLine("同事2得到消息:" +message);
}
}
static void
{
ConcreteMediator m = new ConcreteMediator();
ConcreteColleague
ConcreteColleague
m.Colleague1 = c1;
m.Colleague2 = c2;
c1.Send("吃过饭了吗?");
c2.Send("没有呢,你打算请客?");
Console.ReadKey();
}