中介者模式

2016-08-11  本文已影响0人  tdeblog

1.定义#

用一个中介对象封装一系列的对象交互,中介者使各对象不需要显示地相互作用,从而使其耦合松散,而且可以独立地改变它们之间的交互。中介者模式通过中介者类将之前相互依赖的功能类解耦合,使得相互依赖的功能类之间不直接交互,而是通过中介者类交互。

2.类图#

类图

3.实现#

3.1抽象同事类##

public abstract class Collegue {
    protected Mediator mediator;
    public Collegue(Mediator _mediator) {
        this.mediator = _mediator;
    }
}

3.2具体同事类##

public class ConcreteCollegue1 extends Collegue {
    public ConcreteCollegue1(Mediator mediator) {
        super(mediator);
    }

    public void selfMethod1() {
        //处理本身的方法
    }

    public void depMethod1() {
        //依赖于其它同事类的方法
        super.mediator.doSomething1();
    }

}

public class ConcreteCollegue2 extends Collegue {
    public ConcreteCollegue2(Mediator mediator) {
        super(mediator);
    }

    public void selfMethod2() {
        //处理本身的方法
    }

    public void depMethod2() {
        //依赖于其它同事类的方法
        super.mediator.doSomething1();
    }

}

3.3抽象中介者类##

public abstract class Mediator {

    protected ConcreteCollegue1 concreteCollegue1;
    protected ConcreteCollegue2 concreteCollegue2;

    public void setConcreteCollegue1(ConcreteCollegue1 concreteCollegue1) {
        this.concreteCollegue1 = concreteCollegue1;
    }

    public void setConcreteCollegue2(ConcreteCollegue2 concreteCollegue2) {
        this.concreteCollegue2 = concreteCollegue2;
    }

    public abstract void doSomething1();

    public abstract void doSomething2();

}

3.4具体中介者类##

public class ConcreteMediator extends Mediator {
    @Override
    public void doSomething1() {
        super.concreteCollegue1.selfMethod1();
        super.concreteCollegue2.selfMethod2();
    }

    @Override
    public void doSomething2() {
        super.concreteCollegue1.selfMethod1();
        super.concreteCollegue2.selfMethod2();
    }
}
上一篇下一篇

猜你喜欢

热点阅读