定义:用一个中介对象来封装一系列的对象交互,用来降低多个对象和类之间的通信复杂性。这种模式提供了一个中介类,该类通常处理不同类之间的通信,并支持松耦合,使代码易于维护。多个对象可以互相通信,建立一个中间的中介类完成彼此间的通信,类似于QQ功能,链接多个类似的对象。
优点:
1、降低了类的复杂度,将一对多转化成了一对一。
2、各个类之间的解耦。
3、符合迪米特原则。
使用前:
使用后:
缺点:中介者会庞大,变得复杂难以维护。
实现:以下案例建立一个类似于QQ的功能。单个对象通过QQMeditor于其他对象通信。
1.创建单个的对象的抽象类和实现类:
public abstract class Colleage { private string _name; private string _content; public Colleage(string n) { _name = n; } public string Name { get { return _name;} set { _name = value; } } public string Content { get { return _content;} set{ _content = value; } } public virtual void Talk(){} } public class ColleageA : Colleage { public ColleageA(string name): base(name){ } public override void Talk() { base.Talk(); Debug.Log("ColleageA说: " + Content); } } public class ColleageB : Colleage { public ColleageB(string name) : base(name) { } public override void Talk() { base.Talk(); Debug.Log("ColleageB说: " + Content); } } public class ColleageC : Colleage { public ColleageC(string name) : base(name) { } public override void Talk() { base.Talk(); Debug.Log("ColleageC说: " + Content); } }
2.创建中介类的抽象类和实现类:
public abstract class Meaditor { protected List<Colleage> Colleages = new List<Colleage>(); public virtual void AddColleage(Colleage c){} public virtual void RemoveColleage(Colleage c){} public virtual void Notify(Colleage student){} public virtual void Chart(Colleage A, Colleage B){} } public class QQMeaditor:Meaditor { public override void AddColleage(Colleage c) { Colleages.Add(c); } public override void RemoveColleage(Colleage c) { Colleages.Remove(c); } public override void Notify(Colleage student) { int count = Colleages.Count; for (int i = 0; i < count; i++) { Colleages[i].Talk(); } } public override void Chart(Colleage A, Colleage B) { A.Talk(); B.Talk(); } }
3.创建客户端类,实现具体调用:
public class Client:MonoBehaviour { void Start() { //创建单个对象和中介对象QQ QQMeditor qq = new QQMeditor(); ColleageA a = new ColleageA("A"); ColleageB b = new ColleageB("B"); ColleageB c = new ColleageB("C"); a.Content = "加油!"; b.Content = "-----"; c.Content = "====="; //添加多个对象进管理数组 qq.AddColleage(a); qq.AddColleage(b); qq.AddColleage(c); qq.Notify(a); b.Content = "_________"; c.Content = "+++++++++"; qq.Chart(b, c); } }