用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
using UnityEngine;
using System.Collections;
public class MediatorStructure : MonoBehaviour
{
void Start()
{
ConcreteMediator m = new ConcreteMediator();
ConcreteColleague1 c1 = new ConcreteColleague1(m);
ConcreteColleague2 c2 = new ConcreteColleague2(m);
m.Colleague1 = c1;
m.Colleague2 = c2;
c1.Send("How are you?");
c2.Send("Fine, thanks");
}
}
/// <summary>
///中介者
/// </summary>
abstract class Mediator
{
public abstract void Send(string message,Colleague colleague);
}
/// <summary>
/// 具体中介者
/// </summary>
class ConcreteMediator : Mediator
{
//持有对象
private ConcreteColleague1 _colleague1;
private ConcreteColleague2 _colleague2;
public ConcreteColleague1 Colleague1
{
set { _colleague1 = value; }
}
public ConcreteColleague2 Colleague2
{
set { _colleague2 = value; }
}
public override void Send(string message,Colleague colleague)
{
if (colleague == _colleague1)
{
_colleague2.Notify(message);//如果是对象1发送,那就是对象2接收
}
else
{
_colleague1.Notify(message);
}
}
}
/// <summary>
/// 对象
/// </summary>
abstract class Colleague
{
protected Mediator mediator;
// Constructor
public Colleague(Mediator mediator)
{
this.mediator = mediator;
}
}
/// <summary>
///对象1
/// </summary>
class ConcreteColleague1 : Colleague
{
// Constructor
public ConcreteColleague1(Mediator mediator)
: base(mediator)
{
}
public void Send(string message)
{
mediator.Send(message, this);//传递自身
}
public void Notify(string message)
{
Debug.Log("Colleague1 gets message: "+ message);
}
}
/// <summary>
///对象2
/// </summary>
class ConcreteColleague2 : Colleague
{
// Constructor
public ConcreteColleague2(Mediator mediator)
: base(mediator)
{
}
public void Send(string message)
{
mediator.Send(message, this);
}
public void Notify(string message)
{
Debug.Log("Colleague2 gets message: "+ message);
}
}