中介者模式是用来协调一组同事,这些同事可能互相不直接交流,而是中介者。 在下面的例子中,Colleague A 想聊天,Colleague B 想打架。当他们做一些动作,他们唤醒中介者去做。
中介者类图
中介者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();
}
}
在行为模式中,观察者模式最像中介者,你可以在观察者模式中比较两者。
© 著作权归作者所有