设计模式学习笔记——中介者模式(Mediator)
1.特点:由中介封装一系列对象交互,减少对象间耦合,利于复用。(朋友多)
2.概念:定义一个中介对象来封装系列对象之间的交互。
3.类图:
4.程序实现:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mediator { class Program { static void Main(string[] args) { ConcreteMediator m = new ConcreteMediator(); ConcreteColleague1 c1 = new ConcreteColleague1(m); ConcreteColleague2 c2 = new ConcreteColleague2(m); m.Colleague1 = c1; m.Colleague2 = c2; c1.Send("你吃过了么"); c2.Send("没有呢,你请客?"); Console.Read(); } } abstract class Mediator { public abstract void Send(string message, Colleague colleague); } //抽象同事类 abstract class Colleague { protected Mediator mediator; public Colleague(Mediator mediator) { this.mediator = mediator; } } class ConcreteMediator : Mediator { private ConcreteColleague1 colleague1; private ConcreteColleague2 colleague2; public ConcreteColleague1 Colleague1 { set { this.colleague1 = value; } } public ConcreteColleague2 Colleague2 { set { this.colleague2 = value; } } public override void Send(string message, Colleague colleague) { if (colleague == colleague1) { colleague2.Notify(message); } else { colleague1.Notify(message); } } } 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); } } }