美文网首页
中介者模式

中介者模式

作者: 最美时光在路上 | 来源:发表于2016-10-26 23:15 被阅读0次
  1. 抽象中介者
public abstract class AbstractMediator {
    protected AbstractColleague c1;
    protected AbstractColleague c2;
    public AbstractColleague getC1() {
        return c1;
    }
    public void setC1(AbstractColleague c1) {
        this.c1 = c1;
    }
    public AbstractColleague getC2() {
        return c2;
    }
    public void setC2(AbstractColleague c2) {
        this.c2 = c2;
    }
    //中介者处理方法
    protected abstract void handleRequest();
}
  1. 抽象中介者实现类
public class ConcreteMediator extends AbstractMediator {
    @Override
    protected void handleRequest() {
        super.c1.doSomething();
        super.c2.doSomething();
    }
}
  1. 同事类抽象对象
public abstract class AbstractColleague {
    protected AbstractMediator mediator;
    public AbstractColleague(AbstractMediator mediator) {
        this.mediator = mediator;
    }
    public abstract void doSomething() ;
    public abstract void deputeMethod() ;
}
  1. 同事类抽象对象实现类
public class ConcreteColleague extends AbstractColleague {
    public ConcreteColleague(AbstractMediator mediator) {
        super(mediator);
    }
    @Override
    public void doSomething() {
        //普通方法业务处理
    }
    @Override
    public void deputeMethod() {
        //委托给中介者处理
        super.mediator.handleRequest();
    }
}
  1. 场景使用
    //创建中介者
    AbstractMediator mediator = new ConcreteMediator();
    //创建同事类对象
    AbstractColleague colleague1 = new ConcreteColleague(mediator);
    //同事类对象在中介者对象中注册
    mediator.setC1(colleague1);
    //同事类对象通过中介者进行处理逻辑
    colleague1.deputeMethod();

相关文章

网友评论

      本文标题:中介者模式

      本文链接:https://www.haomeiwen.com/subject/svsjuttx.html