public abstract class Mediator { public abstract void Register(Colleague colleague); public abstract void Relay(Colleague colleague); }
public class ConcreteMediator : Mediator { private List<Colleague> colleagues=new List<Colleague>(); public override void Register(Colleague colleague) { if(!colleagues.Contains(colleague)) { colleagues.Add(colleague); colleague.SetMediator(this); } } public override void Relay(Colleague colleague) { foreach (var item in colleagues) { if (!item.Equals(colleague)) { item.Receive(); } } } }
public abstract class Colleague { protected Mediator mediator; public void SetMediator(Mediator mediator) { this.mediator=mediator; } public abstract void Receive(); public abstract void Send(); }
public class ConcreteColleague1 : Colleague { public override void Receive() { Console.WriteLine("具体同事类1收到请求。"); } public override void Send() { Console.WriteLine("具体同事类1发出请求。"); mediator.Relay(this); } }
public class ConcreteColleague2 : Colleague { public override void Receive() { Console.WriteLine("具体同事类2收到请求。"); } public override void Send() { Console.WriteLine("具体同事类2发出请求。"); mediator.Relay(this); } }