中介者模式(Mediator Pattern)

中介者模式(Mediator Pattern),定义一个中介对象来封装系列对象之间的交互。中介者使各个对象不需要显示地相互引用,从而使其耦合性松散,而且可以独立地改变他们之间的交互。 Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently。

 

中介者模式的组成部分:

1) 抽象中介者(Mediator)角色:抽象中介者角色定义统一的接口用于各同事角色之间的通信。

2) 具体中介者(Concrete Mediator)角色:具体中介者角色通过协调各同事角色实现协作行为。为此它要知道并引用各个同事角色。

3) 同事(Colleague)角色:每一个同事角色都知道对应的具体中介者角色,而且与其他的同事角色通信的时候,一定要通过中介者角色协作。

来自《设计模式》一书的类图:


由于中介者的行为与要使用的数据与具体业务紧密相关,抽象中介者角色提供一个能方便很多对象使用的接口是不太现实的。所以抽象中介者角色往往是不存在 的,或者只是一个标示接口。如果有幸能够提炼出真正带有行为的抽象中介者角色,我想同事角色对具体中介者角色的选择也是策略的一种应用。

代码:

    public abstract class Mediator
    {
        public abstract void Send(string message, Colleage c);
    }
    public class ConcreteMediator : Mediator
    {
        public ConcreteColleague1 c1{get;set;}
        public ConcreteColleague2 c2 { get; set; }
        public override void Send(string message,Colleage c)
        {
            if (c == c1)
            {
                this.c1.Notify(message);
            }
            else
            {
                this.c2.Notify(message);
            }
        }
    }
    public abstract class Colleage
    {
        protected Mediator mediator;
        public Colleage(Mediator m)
        {
            this.mediator = m;
        }
    }
    public class ConcreteColleague1 : Colleage
    {
        public ConcreteColleague1(Mediator mediator):base(mediator)
        {}
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
        public void Notify(string message)
        {
            Console.Write("ConcreteCollage1 action " + message);
        }
    }
    public class ConcreteColleague2 : Colleage
    {
        public ConcreteColleague2(Mediator m):base( m)
        {}
        public void Send(string message)
        {
            mediator.Send(message, this);
        }
        public void Notify(string message)
        {
            Console.Write("ConcreteCollage2 action " + message);
        }
    }

调用:

            ConcreteMediator m = new ConcreteMediator();
            //让同事认识中介者对象
            ConcreteColleague1 c1 = new ConcreteColleague1(m);
            ConcreteColleague2 c2 = new ConcreteColleague2(m);
            //让中介者认识具体对象
            m.c1 = c1;
            m.c2 = c2;
            //具体发送的消息都是通过中介者转发
            c1.Send("吃饭了吗");
            c2.Send("你请客?");

 

posted @ 2013-11-05 15:59  nygfcn  阅读(299)  评论(0)    收藏  举报