博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
行为型模式之十:中介者模式
阅读量:6865 次
发布时间:2019-06-26

本文共 1667 字,大约阅读时间需要 5 分钟。

  hot3.png

中介者模式是用来协调一组同事,这些同事可能互相不直接交流,而是中介者。 在下面的例子中,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 mediatorclass 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 colleagueclass ColleagueA extends Colleague {   public ColleagueA(IMediator mediator) {    this.mediator = mediator;  }   @Override  public void doSomething() {    this.mediator.talk();    this.mediator.registerA(this);  }} //concrete colleagueclass 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();  }}

在行为模式中,观察者模式最像中介者,你可以在观察者模式中比较两者。

转载于:https://my.oschina.net/markho/blog/498249

你可能感兴趣的文章