中介者模式(Mediator):用一个中介对象来封装一序列的对象交互。中介者使各对象不需要显式地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
namespace MediatorDesign { public abstract class Mediator { public abstract void Send(string message, Colleague colleague); } 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); } } public class ConcreteMediator : Mediator { protected ConcreteColleague1 colleague1; protected 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); } } } }
测试代码:
ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("Hello."); c2.Send("Hi.");
时间: 2024-11-10 22:43:08