Clark To Do The blog of Clark

Java设计模式:中介者模式

注:本文为译文,原文出处java-design-patterns-in-stories

中介者设计模式应用于协作一组同事. 那些同事互相之间不会直接沟通, 而是通过中介者.

下面的例子中, 同事A想聊天, 同事B想打架. 当他们做出一些行为时(例如: doSomething()), 会调用中介者去做那些事儿.

中介者模式类图

mediator-design-pattern

中介者模式Java代码

package designpatterns.mediator;

interface IMediator {
    public void fight();
    public void talk();
    public void registerA(ColleagueA a);
    public void registerB(ColleagueB a);
}

//concrete mediator
class ConcreteMediator implements IMediator{

    ColleagueA talk;
    ColleagueB fight;

    public void registerA(ColleagueA a){
        talk = a;
    }

    public void registerB(ColleagueB b){
        fight = b;
    }

    public void fight(){
        System.out.println("Mediator is fighting");
        //let the fight colleague do some stuff
    }

    public void talk(){
        System.out.println("Mediator is talking");
        //let the talk colleague do some stuff
    }
}

abstract class Colleague {
    IMediator mediator;
    public abstract void doSomething();
}

//concrete colleague
class ColleagueA extends Colleague {

    public ColleagueA(IMediator mediator) {
        this.mediator = mediator;
    }

    @Override
    public void doSomething() {
        this.mediator.talk();
        this.mediator.registerA(this);
    }
}

//concrete colleague
class ColleagueB extends Colleague {
    public ColleagueB(IMediator mediator) {
        this.mediator = mediator;
        this.mediator.registerB(this);
    }

    @Override
    public void doSomething() {
        this.mediator.fight();
    }
}

public class MediatorTest {
    public static void main(String[] args) {
        IMediator mediator = new ConcreteMediator();

        ColleagueA talkColleague = new ColleagueA(mediator);
        ColleagueB fightColleague = new ColleagueB(mediator);

        talkColleague.doSomething();
        fightColleague.doSomething();
    }
}

在其他行为模式中, 观察者模式是与中介者模式最相似的. 你可以阅读观察者模式来比较两者的不同之处.

comments powered by Disqus