类内部定义接口

类内部实现接口,实现责任链

 

public class InterfacePropertyDemo {
  interface Child {
    DeadLockDemo method(String strKey, String strValue);
  }


  // 存入匿名类,类似责任链, 里面存储的是方法的集合
  private List<Child> myChildren = new CopyOnWriteArrayList<>();

  public void addChild(Child child) {
    this.myChildren.add(child);
  }

  public static void main(String[] args) {

    InterfacePropertyDemo demo = new InterfacePropertyDemo();


    demo.addChild((key, value) -> new DeadLockDemo(key, value));
    demo.addChild((key, value) -> new DeadLockDemo(key + "_1", value + "_1"));
    demo.addChild(new Child() {
      @Override
      public DeadLockDemo method(String strKey, String strValue) {
        return new DeadLockDemo(strKey + "_2", strValue + "_2");
      }
    });


    String strKey = "strKey";
    String strValue = "strValue";

    List<DeadLockDemo> lstResult =
        demo.myChildren.stream().map(obj -> obj.method(strKey, strValue)).collect(Collectors.toList());
  }
}

 

posted @ 2021-06-17 09:52  龘人上天  阅读(129)  评论(0编辑  收藏  举报