- 简介
用一个中介对象来封装一系列的对象交互。中介者使各对象不需要显示地相互引用,从而使其耦合松散,而且可以独立地改变它们之间的交互。
- 中介模式的缺点
- 中介者模式很容易在系统中应用,也很容易在系统中误用。当系统出现了‘多对多’交互复杂的对象群,不能急于使用中介者模式。
- 中介者模式的优点
- 具体中介者类控制了集中化,于是就把交互复杂性变味了中介者的复杂性,这就使得中介者会变得比任何一个中介类都复杂。
- 实例:
//中介基类
abstract class Mediator
{
public abstract void Send(string message,Colleague colleague);
}
//同事类
abstract class Colleague
{
protected Mediator mediator;
public Colleague(Mediator mediator){
this.mediator = mediator;
}
}
class ConcreteMediator : Mediator
{
private ConcreteColleague1 cooleague1;
private ConcreteColleague2 cooleague2;
public ConcreteColleague1 Colleague1
{
set{ Colleague1 = value; }
}
public ConcreteColleague2 Colleague2
{
set{ Colleague2 = value; }
}
public override void Send(stirng message,Colleague colleague){
if(colleague == Colleague1)
{
Colleague1.Notify(message);
}else{
Colleague2.Notify(message);
}
}
}
class ConcreteColleague1 :Colleague
{
public ConcreteColleague1 (Mediator mediator):base(mediator)
[
]
public void Send(string message)
{
mediator.Send(message,this);
}
public void Notify(string message)
{
Console.WriteLine("同事1得到的消息是:"+message);
}
}
class ConcreteColleague2 :Colleague
{
public ConcreteColleague2 (Mediator mediator):base(mediator)
[
]
public void Send(string message)
{
mediator.Send(message,this);
}
public void Notify(string message)
{
Console.WriteLine("同事2得到的消息是:"+message);
}
}
static void Main(string[] args){
//创建中介类
ConcreteMediator M = new ConcreteMediator();
//
ConcreteColleague1 c1 = new ConcreteColleague1(m);
ConcreteColleague2 c1 = new ConcreteColleague2(m);
m.Colleague1 = c1;
m.Colleague2 = c2;
c1.Send("message1");
c2.Send("message2");
Console.Read();
}
网友评论