中介者模式:用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显式地互相引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
中介者模式很容易在系统中应用,也很容易在系统中误用。当系统出现了‘多对多’交互复杂的对象群时,不要急于使用中介者模式,而要反思系统设计上是否合理。
中介者模式优点:
Mediator的出现,减少了各个Colleague的耦合,使得可以独立地改变和复用各个Colleague类和Mediator。由于把对象如何协作做了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的对象就从对象各自本身的行为转移到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。
由于ConcreteMediator控制了集中化,于是把交互复杂性变为了中介者的复杂性,这就使得中介这会变得比任何一个ConcreteColleague都复杂。
public abstract class Mediator { public abstract void Send(string message, Colleague colleague); }
public class ConcreteMediator:Mediator { //需要了解所有的具体对象: public ConcreteColleague1 colleague1 { private get; set; } public ConcreteColleague2 colleague2 { private get; set; } public override void Send(string message, Colleague colleague) { if(colleague==colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } }
public abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } }
public 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); } }
public 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); } }
class Program { static void Main(string[] args) { ConcreteMediator mediator = new ConcreteMediator(); ConcreteColleague1 colleague1 = new ConcreteColleague1(mediator); ConcreteColleague2 colleague2 = new ConcreteColleague2(mediator); mediator.colleague1 = colleague1; mediator.colleague2 = colleague2; colleague1.Send("吃过饭了吗?"); colleague2.Send("没呢,你打算请客?"); } }
http://www.cnblogs.com/walden1024/archive/2015/05/25/4529107.html