10

考虑下面的类

class A{
    public void init(){
        //do this first;
    }
    public void atEnd(){
        //do this after init of base class ends
    }
}

class B1 extends A{

    @Override
    public void init()
    {
        super.init();
        //do new stuff.
        //I do not want to call atEnd() method here...
    }
}

我有几个已经开发的 B1、B2、... Bn 子类。它们都扩展了 A 类。如果我想在所有这些中添加新功能,最好的方法是在 A 类中的方法中定义它。但条件是该方法应该总是在之前自动调用子类的 init() 方法结束。这样做的一种基本方法是在子类的 init() 方法的末尾再次添加 atEnd() 方法调用。但是有没有其他方法可以巧妙地做到这一点?

4

4 回答 4

21

一种方法是制作init()final 并将其操作委托给第二个可覆盖的方法:

abstract class A {
  public final void init() {
    // insert prologue here
    initImpl();
    // insert epilogue here
  }
  protected abstract void initImpl();
}

class B extends A {
  protected void initImpl() {
    // ...
  }
}

每当有人调用init()时,prologue 和 epilogue 都会自动执行,派生类不必做任何事情。

于 2012-05-17T11:58:19.033 回答
4

Another thought would be to weave in an aspect. Add before and after advice to a pointcut.

于 2012-05-17T11:59:45.657 回答
3

Make init() final,并为人们提供一个单独的方法来覆盖init()中间的调用:

class A{
    public final void init(){
        //do this first;
    }

    protected void initCore() { }

    public void atEnd(){
        //do this after init of base class ends
    }
}

class B1 extends A{

    @Override
    protected void initCore()
    {
        //do new stuff.
    }
}
于 2012-05-17T11:57:10.210 回答
0

其他答案是合理的解决方法,但要解决确切的问题:不,没有办法自动执行此操作。您必须显式调用super.method().

于 2019-03-13T15:06:14.303 回答