设计模式:中间人模式
中间人设计模式是用于协作一组同事。这些同事相互之间不直接沟通,而是通过中介。
在下面的例子中,同事A想要说话,同事B想要打架。当他们做动作(例如doSomething)的时候,他们调用中间人去做那些动作或事情。
1、中间人类图
2、代码实例
package com.leon.mediator;interface IMediator {public void fight();public void talk();public void registerA(ColleagueA a);public void registerB(ColleagueB b);}//具体的中间人class ConcreteMediator implements IMediator {ColleagueA a;ColleagueB b;@Overridepublic void fight() {// TODO Auto-generated method stubSystem.out.println("中间人在打架!");}@Overridepublic void talk() {// TODO Auto-generated method stubSystem.out.println("中间人在说话!");}@Overridepublic void registerA(ColleagueA a) {// TODO Auto-generated method stubthis.a = a;}@Overridepublic void registerB(ColleagueB b) {// TODO Auto-generated method stubthis.b = b;}}abstract class Colleague {IMediator mediator;public abstract void doSomething();}//同事Aclass ColleagueA extends Colleague {public ColleagueA(IMediator mediator) {this.mediator = mediator;this.mediator.registerA(this);}@Overridepublic void doSomething() {// TODO Auto-generated method stubthis.mediator.talk();}}//同事Bclass ColleagueB extends Colleague {public ColleagueB(IMediator mediator) {this.mediator = mediator;this.mediator.registerB(this);}@Overridepublic void doSomething() {// TODO Auto-generated method stubthis.mediator.fight();}}public class Main {public static void main(String[] args) {IMediator mediator = new ConcreteMediator();ColleagueA talkColleague = new ColleagueA(mediator);ColleagueB fightColleague = new ColleagueB(mediator);talkColleague.doSomething();fightColleague.doSomething();}}
?
?在其他行为类型的模式中,观察者模式跟中间人模式最为相似。你可以阅读下观察者模式来比较下两者的不同。