设计模式——4.中介者模式
Posted sylvan
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式——4.中介者模式相关的知识,希望对你有一定的参考价值。
中介者模式(Mediator)简介:
用一个中介对象来封装一系列对象的交互。中介者模式是各个对象不再显式的相互引用,从而降低耦合,并且可以独立的改变各个对象之间的交互。
中介者模式结构
Colleague类及其子类:
public abstract class Colleague
{
protected Mediator mediator = null;
public Colleague(Mediator mediator) {
this.mediator = mediator;
}
public abstract void request(string msg);
}
public class Colleague1 : Colleague
{
public Colleague1(Mediator mediator) : base(mediator) { }
public void echo(string msg) {
Console.WriteLine("Colleague1 got the msg : "+msg);
}
public override void request(string msg)
{
mediator.sendMsg(this,msg);
}
}
public class Colleague2 : Colleague
{
public Colleague2(Mediator mediator) : base(mediator) { }
public void echo(string msg) {
Console.WriteLine("Colleague2 got the msg : " + msg);
}
public override void request(string msg)
{
mediator.sendMsg(this,msg);
}
}
中介者类:
public abstract class Mediator
{
public abstract void sendMsg(Colleague colleague,string msg);
}
public class TheMediator : Mediator
{
public Colleague1 C1{ get; set; }
public Colleague2 C2 { get; set; }
public override void sendMsg(Colleague colleague, string msg)
{
if (colleague == C1)
{
C2.echo(msg);
}
else {
C1.echo(msg);
}
}
}
客户端测试代码:
class Program
{
static void Main(string[] args)
{
TheMediator theMediator = new TheMediator();
Colleague1 colleague1 = new Colleague1(theMediator);
Colleague2 colleague2 = new Colleague2(theMediator);
theMediator.C1 = colleague1;
theMediator.C2 = colleague2;
colleague1.request("Are you OK?");
colleague2.request("I'm OK!");
Console.ReadKey();
}
}
中介者模式的优点及缺点
优点:
使用中介者模式之后,使用的类无论是从类外部获取信息还是向外部传递信息,都通过中介者类来完成;当需要做出一些修改时,可以大大减小后期修改维护时的难度。
缺点:
当过多的类都通过中介者进行沟通时,中介者类中会出现操作接口爆炸的情况,此时,我们可以适当搭配其他设计模式来减轻中介者类的负担。
以上是关于设计模式——4.中介者模式的主要内容,如果未能解决你的问题,请参考以下文章