设计模式(中介者模式)

中介者模式提供一个统一的中介接口Mediator,与多个目标对象交互。如下图:

设计模式(中介者模式)

代码如下:

  • Mediator
public abstract class Mediator {

    public abstract void notice(String content);

}
  • ConcreteMediator
public class ConcreteMediator extends Mediator {

    

    //这里可以有多个目标

    //private Target target1

    //private Target target2

    private Target target;

    

    //也可以构造addTarget以维护一个处理对象的列表

    public ConcreteMediator(){

        target = new ConcreteTarget();

    }

    

    @Override

    public void notice(String content) {

        target.doSomething(content);

    }

}
  • Target
public abstract class Target {

    public abstract void doSomething(String content);

}
  • ConcreteTarget
public class ConcreteTarget extends Target {



    @Override

    public void doSomething(String content) {

        System.out.println("ConcreteTarget doSomething" + content);

    }

}
  • App 测试类
public class App {



    public static void main(String[] args) {

        Mediator mediator = new ConcreteMediator();

        mediator.notice("Fredric");

        

    }

}

你可能感兴趣的:(中介者模式)