简体   繁体   English

如何强制派生类在多层调用超类方法?

[英]How to force derived class to call super class method at multiple layers?

I am trying to find the most elegant way to allow a child and parent to react to an event initiated by the grandparent.我试图找到最优雅的方式,让孩子和父母对祖父母发起的事件做出反应。 Here's a naive solution to this:这是一个天真的解决方案:

abstract class A {
    final public void foo() {
        // Some stuff here
        onFoo();
    }

    protected abstract void onFoo();
}

abstract class B extends A {
    @Override
    final protected void onFoo() {
        // More stuff here
        onOnFoo();
    }

    protected abstract void onOnFoo();
}

class C extends B {
    @Override
    protected void onOnFoo() {
        // Even more stuff here
    }
}

So basically, I'm trying to find the best way to allow all related classes to perform some logic when foo() is called.所以基本上,我试图找到最好的方法来允许所有相关的类在 foo() 被调用时执行一些逻辑。 For stability and simplicity purposes I prefer if it is all done in order, although it's not a requirement.出于稳定性和简单性的目的,我更喜欢按顺序完成所有操作,尽管这不是必需的。

One other solution I found involves storing all the event handlers as some form of Runnable:我发现的另一种解决方案涉及将所有事件处理程序存储为某种形式的 Runnable:

abstract class A {
    private ArrayList<Runnable> fooHandlers = new ArrayList<>();

    final public void foo() {
        // Some stuff here
        for(Runnable handler : fooHandlers) handler.run();
    }

    final protected void addFooHandler(Runnable handler) {
        fooHandlers.add(handler);
    }
}

abstract class B extends A {
    public B() {
        addFooHandler(this::onFoo);
    }

    private void onFoo() {
        // Stuff
    }
}

class C extends B {
    public C() {
        addFooHandler(this::onFoo);
    }

    private void onFoo() {
        // More stuff
    }
}

This method is certainly preferable to the first.这种方法当然比第一种更可取。 However I am still curious if there is a better option.但是我仍然很好奇是否有更好的选择。

Have you considered the Template Method pattern?你考虑过模板方法模式吗? It works well to define a high level method that delegates to derived types to fill-in the gaps.它可以很好地定义一个高级方法,该方法委托派生类型来填补空白。

What about this by calling the super method?通过调用 super 方法怎么办?

class A {
  void foo() {
    System.out.println("Some stuff here");
  }
}

class B extends A {
  @Override
  void foo() {
    super.foo();
    System.out.println("More stuff here");
  }
}

class C extends B {
  @Override
  void foo() {
    super.foo();
    System.out.println("Even more stuff here");
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM