设计模式之 中介者模式

当多个类之间需要建立联系时,为了避免多个类之间的耦合,通过一个“中介者”类专门负责多个类之间的信息交换。

 

现有婚姻介绍所为例:韩梅梅和李雷(有车有房,年龄稍大)都在婚介所注册了会员,韩梅梅在听了婚介所工作人员对李雷的介绍后决定约李雷见面,于是婚介所工作人员将话带到了李雷那里。代码如下:

中介抽象类:

abstract class Mediator
{
public abstract void Register(People people);

public abstract void SetMessage(string message, People from, string to);
}

 

继承了中介抽象类具体的婚介所类:

代码
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;
}
}
}
}

会员基类:

代码
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);
}

继承了会员基类的男人类:

代码
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));
}
}

继承了会员基类的女人类:

代码
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}");
}
}

测试代码如下:

代码
static void Main(string[] args)
{
MatrimonialMediator matrimonialMediator
= new MatrimonialMediator();
People HanMeimei
= new Woman("韩美美", matrimonialMediator);
People LiLei
= new Man("李雷", matrimonialMediator);

HanMeimei.SetMessage(
"约在XXXX见面", "李雷");
Console.Read();
}

运行结果:

看了有戏!!

 

 

 

posted @ 2009-12-16 15:24  会长  阅读(241)  评论(0编辑  收藏  举报