using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace Mediator{//抽象果园类public abstract class Orchard{protected Orchardist orchardist; //果农实例引用public Orchard(Orchardist orchardist){this.orchardist = orchardist;}public abstract void PlantRemote(); //种植异地水果抽象方法public abstract void Plant(); //种植水果抽象方法}//北京果园类public class BJOrchard : Orchard{public BJOrchard(Orchardist orchardist): base(orchardist) { }public override void PlantRemote() //北京果园种植异地水果方法{this.orchardist.PlantRemote(this);}public override void Plant() //北京果园种植水果方法{Console.WriteLine(\"种植北京水果\");}}//上海果园类public class SHOrchard : Orchard{public SHOrchard(Orchardist orchardist): base(orchardist) { }public override void PlantRemote() //上海果园种植异地水果方法{this.orchardist.PlantRemote(this);}public override void Plant() //上海果园种植水果方法{Console.WriteLine(\"种植上海水果\");}}//抽象果农类public abstract class Orchardist{public abstract void PlantRemote(Orchard orchard); //种植异地水果}//北京上海果农public class BJSHOrchardist : Orchardist{Orchard bjOrchard; //北京果园Orchard shOrchard; //上海果园public Orchard BJOrchard { set { bjOrchard = value; } }public Orchard SHOrchard { set { shOrchard = value; } }public override void PlantRemote(Orchard orchard){if (orchard == this.bjOrchard){Console.Write(\"北京果园\");shOrchard.Plant(); //种植上海水果}else if (orchard == this.shOrchard){Console.Write(\"上海果园\");bjOrchard.Plant(); //种植北京水果}}}class Program{static void Main(string[] args){BJSHOrchardist orchardist = new BJSHOrchardist(); //创建果农实例Orchard bjBJOrchard = new BJOrchard(orchardist); //创建北京果园Orchard shBJOrchard = new SHOrchard(orchardist); //创建上海果园orchardist.BJOrchard = bjBJOrchard;orchardist.SHOrchard = shBJOrchard;bjBJOrchard.PlantRemote(); //北京果园种植上海水果shBJOrchard.PlantRemote(); //上海果园种植北京水果Console.ReadKey();}}}
代码分析:
本实例代码实现了中介者模式,首先创建了抽象果园类 Orchard 及其派生类 BJOrchard 和SHOrchard,然后创建了抽象果农类Orchardist及其派生类BJSHOrchardist,该类起到的是中介者的作用。BJSHOrchardist类主要实现了BJOrchard和SHOrchard的互相调用,但这两个类并不互相引用。当北京果园BJOrchard需要种植上海水果时,BJOrchard调用PlantRemote方法,而该方法其实是由果农类BJSHOrchardist调用上海果园SHOrchard的Plant方法种植上海水果。此时,对于BJOrchard类来说,与SHOrchard类的交互是透明的。这就是中介者在中间所起到的作用。
说明:
中介者模式主要通过定义一个中介者类来封装一系列对象间的相互调用,中介者类中使各个需要互相调用的类之间不必互相引用,实现了类之间的松耦合,而且在中介者类中还可以独立的去改变这些类之间的调用方式。