使用中介模式,大家通过往中介发消息,和从中介接受消息。从而避免了多个端之间的耦合。就像你看房,你不需要联系各个房东,你只需要联系中介,由中介去联系各个房东和各个租客。
abstract class Mediator
{
public abstract void Send(string message, Colleague colleague);
}
abstract class Colleague
{
protected Mediator mediator;
public Colleague(Mediator mediator)
{
this.mediator = mediator;
}
public abstract void Notify(string message);
}
class ConcreteColleague : Colleague
{
public string Name { get; set; }
public ConcreteColleague(Mediator mediator) : base(mediator) { }
public void Send(string message)
{
mediator.Send(message, this);
}
public override void Notify(string message)
{
Console.WriteLine(string.Format("{0}收到消息:{1}", Name, message));
}
}
class ConcreteMediator : Mediator
{
IList<Colleague> _colleagueList = new List<Colleague>();
public void AddColleague(Colleague colleague)
{
_colleagueList.Add(colleague);
}
public void RemoveColleague(Colleague colleague)
{
_colleagueList.Remove(colleague);
}
public override void Send(string message, Colleague colleague)
{
foreach (Colleague coll in _colleagueList)
{
if (coll == colleague) continue;
coll.Notify(message);
}
}
}
ConcreteMediator ccm = new ConcreteMediator();
ConcreteColleague ccA = new ConcreteColleague(ccm);
ccA.Name = "中国";
ConcreteColleague ccB = new ConcreteColleague(ccm);
ccB.Name = "巴基斯坦";
ConcreteColleague ccC = new ConcreteColleague(ccm);
ccC.Name = "孟加拉国";
ccm.AddColleague(ccA);
ccm.AddColleague(ccB);
ccm.AddColleague(ccC);
ccA.Send("我们是好朋友啊");
巴基斯坦收到消息:我们是好朋友啊
孟加拉国收到消息:我们是好朋友啊