[译]Java 设计模式之中介者

时间:2021-08-13 16:59:54

(文章翻译自Java Design Pattern: Mediator)

中介者设计模式被用于一组的同事进行协作。这些同事不彼此进行直接的交流联系,但是是通过中介者。

在下面的例子中,A同事想去说话,B同事先去打架。当他们做些事情时候他们调用了中介者的方法去做这些。

中介者模式类图

[译]Java 设计模式之中介者

中介者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();
}
}

在其他的行为模式中,观察者是和中介者最相似的。你可以读下观察者模式来比较下他们的不同。