当多个类之间需要建立联系时,为了避免多个类之间的耦合,通过一个“中介者”类专门负责多个类之间的信息交换。
现有婚姻介绍所为例:韩梅梅和李雷(有车有房,年龄稍大)都在婚介所注册了会员,韩梅梅在听了婚介所工作人员对李雷的介绍后决定约李雷见面,于是婚介所工作人员将话带到了李雷那里。代码如下:
中介抽象类:
abstract class Mediator
{
public abstract void Register(People people);
public abstract void SetMessage(string message, People from, string to);
}
继承了中介抽象类具体的婚介所类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class MatrimonialMediator:Mediator
{
private List<People> _list = new List<People>();
public override void Register(People people)
{
_list.Add(people);
}
public override void SetMessage(string message, People from, string to)
{
Console.WriteLine("{0}通过中介对{1}说:{2}", from.Name, to, message);
foreach (var item in _list)
{
if (item.Name == to)
{
item.RecevieMessage(message,from.Name);
break;
}
}
}
}
会员基类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
abstract class People
{
private string _name;
private Mediator _mediator;
public Mediator Mediator
{
get { return _mediator; }
}
public string Name
{
get { return _name; }
}
public People(string name, Mediator mediator)
{
_name = name;
_mediator = mediator;
_mediator.Register(this);
}
public abstract void SetMessage(string message,string to);
public abstract void RecevieMessage(string message,string from);
}
继承了会员基类的男人类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Man:People
{
public Man(string name,Mediator mediator)
: base(name, mediator)
{
}
public override void SetMessage(string message,string to)
{
this.Mediator.SetMessage(message, this, to);
}
public override void RecevieMessage(string message, string from)
{
Console.WriteLine(string.Format("{0}(男)收到了{1}的消息:{2}", this.Name, from, message));
}
}
继承了会员基类的女人类:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
class Woman:People
{
public Woman(string name, Mediator mediator)
: base(name, mediator)
{
}
public override void SetMessage(string message, string to)
{
this.Mediator.SetMessage(message, this, to);
}
public override void RecevieMessage(string message, string from)
{
Console.WriteLine("{0}(女)收到了{1}的消息:{2}");
}
}
测试代码如下:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
static void Main(string[] args)
{
MatrimonialMediator matrimonialMediator = new MatrimonialMediator();
People HanMeimei = new Woman("韩美美", matrimonialMediator);
People LiLei = new Man("李雷", matrimonialMediator);
HanMeimei.SetMessage("约在XXXX见面", "李雷");
Console.Read();
}
运行结果:
看了有戏!!