第二十五章 中介者模式

中介者模式(Mediator):用一个中介对象来封装一系列的对象交互。中介者使对象不需要显示的相互引用,从而使其耦合松散,而且可以独立的改变它们之间的交互。

优点:Mediator的出现减少了各个Colleague的耦合,使得可以独立改变和复用各个Colleague类和Mediator。由于把对象如何协作进行了抽象,将中介作为一个独立的概念并将其封装在一个对象中,这样关注的重点就从对象各自的行为转移到它们之间的交互上来,也就是站在一个更宏观的角度去看待系统。

缺点:由于ConcreteMediator控制了集中化,于是就把交互复杂性变为了中介者的复杂性,这就使得中介者会变得比任何一个ConcreteColleague都复杂。

应用场景:一般应用于一组对象以定义良好但是复杂的方式进行通信的场合;以及想定义一个分布在多个类中的行为,而又不想生成太多子类的场合。

/**
 * Created by hero on 16-4-11.
 */
public abstract class Mediator {
    public abstract void send(String message, Colleague colleague);
}
/**
 * Created by hero on 16-4-11.
 */
public class ConcreteMediator extends Mediator {
    private ConcreteColleague1 concreteColleague1;
    private ConcreteColleague2 concreteColleague2;

    @Override
    public void send(String message, Colleague colleague) {
        if (colleague instanceof ConcreteColleague1) {
            concreteColleague2.notify(message);
        } else {
            concreteColleague1.notify(message);
        }
    }

    public ConcreteColleague1 getConcreteColleague1() {
        return concreteColleague1;
    }

    public void setConcreteColleague1(ConcreteColleague1 concreteColleague1) {
        this.concreteColleague1 = concreteColleague1;
    }

    public ConcreteColleague2 getConcreteColleague2() {
        return concreteColleague2;
    }

    public void setConcreteColleague2(ConcreteColleague2 concreteColleague2) {
        this.concreteColleague2 = concreteColleague2;
    }
}
/**
 * Created by hero on 16-4-11.
 */
public abstract class Colleague {
    protected Mediator mediator;

    public Colleague(Mediator mediator) {
        this.mediator = mediator;
    }
}
/**
 * Created by hero on 16-4-11.
 */
public class ConcreteColleague1 extends Colleague {
    public void send(String message) {
        mediator.send(message, this);
    }

    public void notify(String message) {
        System.out.println("colleague 1 receives message: " + message);
    }

    public ConcreteColleague1(Mediator mediator) {
        super(mediator);
    }
}
/**
 * Created by hero on 16-4-11.
 */
public class ConcreteColleague2 extends Colleague {
    public void send(String message) {
        mediator.send(message, this);
    }

    public void notify(String message) {
        System.out.println("colleague 2 receives message: " + message);
    }

    public ConcreteColleague2(Mediator mediator) {
        super(mediator);
    }
}
public class Main {

    public static void main(String[] args) {
        ConcreteMediator mediator = new ConcreteMediator();
        ConcreteColleague1 concreteColleague1 = new ConcreteColleague1(mediator);
        ConcreteColleague2 concreteColleague2 = new ConcreteColleague2(mediator);
        mediator.setConcreteColleague1(concreteColleague1);
        mediator.setConcreteColleague2(concreteColleague2);
        concreteColleague1.send("吃了吗?");
        concreteColleague2.send("没,你请客?");
    }
}

 

posted @ 2016-04-11 22:58  偶尔会寂寞  阅读(125)  评论(0编辑  收藏  举报