如何确保重载的方法在Java中最后调用另一个方法?

时间:2019-05-16 18:52:41

标签: java

我有一个抽象类Task,具有两个方法execute()finish(),如下所示:

abstract class Task {
  abstract void execute();

  private void finish() {
    // Do something...
  }
}

如何确保execute()的子类中的重载方法Task隐式地调用finish()作为最后一条语句?

2 个答案:

答案 0 :(得分:9)

我不认为有任何“强制”子类调用方法的方法,但是您可以尝试某种 template method 方法:

abstract class Foo {
  protected abstract void bar();     // <--- Note protected so only visible to this and sub-classes

  private void qux() {
    // Do something...
  }

  // This is the `public` template API, you might want this to be final
  public final void method() {
    bar();
    qux();
  }
}

公共method是入口点,先调用抽象bar,然后调用私有qux方法,这意味着所有子类都遵循模板模式。但是,这当然不是万能药,子类可以简单地忽略公共method

答案 1 :(得分:2)

您可以创建一个实现[AutoCloseable]接口的ExecutorCloseable类,例如:

public class ExecutorCloseable extends Foo implements AutoCloseable 
{
  @Override
  public void execute() 
  {
    // ...
  }

  @Override           //this one comes from AutoCloseable
  public void close() //<--will be called after execute is finished
  {
     super.finish();
  }
 }

您可以这样称呼(愚蠢的main()示例):

 public static void main(String[] args) 
 {
     try (ExecutorCloseable ec = new ExecutorCloseable ()) 
     {

        ec.execute();

     } catch(Exception e){
        //...
     } finally {
       //...
    }
 }

希望这很有道理,我真的不知道您如何调用这些方法,也不知道如何创建类。嘿,这是一个尝试:)

为此,finish()上的Foo方法应为protectedpublic(推荐第一个)。