GoF中定义:
定义一个接口来封装一群对象的互动行为
中介者通过移除对象之间的引用
以减少他们之间的耦合度
并且能改变它们之间的互动独立性
游戏做的越大,系统划分的也就越多
如事件系统,关卡系统,信息系统,界面系统等。
系统切分越细,就意味着系统之间的沟通越复杂
单一系统引入太多其他系统的功能,不利于单一系统的转换和维护
单一系统被过多的系统所依赖,不利于接口的更改,容易牵一发而动全身
由于需要提供给其他系统操作,系统的接口可能会过于庞大,不容易维护
using UnityEngine; public abstract class Mediator { public abstract void SendMessage(Colleague theColleague,string Message); } public abstract class Colleague { protected Mediator m_Mediator = null; public Colleague(Mediator theMediator) { m_Mediator = theMediator; } public abstract void Request(string Message); } public class ConcreateColleague1 : Colleague { public ConcreateColleague1(Mediator theMediator) : base(theMediator) { } public void Action() { m_Mediator.SendMessage(this,"Colleage1发出通知"); } public override void Request(string Message) { Debug.Log("ConcreateColleague1.Request:" + Message); } } public class ConcreateColleague2 : Colleague { public ConcreateColleague2(Mediator theMediator) : base(theMediator) { } public void Action() { m_Mediator.SendMessage(this,"Colleage2发出通知"); } public override void Request(string Message) { Debug.Log("ConcreateColleague2.Request:" + Message); } } public class ConcreteMediator : Mediator { ConcreateColleague1 m_Colleague1 = null; ConcreateColleague2 m_Colleague2 = null; public void SetColleague1(ConcreateColleague1 theColleague) { m_Colleague1 = theColleague; } public void SetColleague2(ConcreateColleague2 theColleague) { m_Colleague2 = theColleague; } public override void SendMessage(Colleague theColleague, string Message) { if (m_Colleague1 == theColleague) m_Colleague2.Request(Message); if (m_Colleague2 == theColleague) m_Colleague1.Request(Message); } }
先产生中介者ConcreteMediator的对象之后
接着产生两个Colleague对象
并将其设置给中介者
分别调用两个Colleague对象的Action方法
查看信息是否通过Mediator传递给Colleague
文章整理自书籍《设计模式与游戏完美开发》 菜升达 著