单例 + 抽象 class 问题

Singleton + Abstract class issue

我正在尝试定义此继承:

public abstract class GameAction extends Observable {
  protected static GameAction instance = null;

  protected GameAction() {
    // Exists only to defeat instantiation.
  }

  //All GameActions are singletons
  public static abstract GameAction getInstance();
}

public class ChooseAnswerAction extends GameAction {

  protected ChooseAnswerAction() {
    // Exists only to defeat instantiation.
  }

  //All GameActions are singletons
  @Override
  public static GameAction getInstance() {
    if(instance == null) {
      instance = new ChooseAnswerAction();
    }
    return instance;
  }
}

问题是第二个class中的getInstance()方法在他父亲身上找不到相同的方法,因此要求我删除@Override

同样在父 class 上,我收到以下错误:

The abstract method getInstance in type GameAction can only set a visibility modifier, one of public or protected

我能解决这个错误的唯一方法是去掉 static 修饰符,但我需要它...

感谢您的宝贵时间!

这是我在单例上的 link。因为 Aleksey Shipilёv 已经做了一个非常详细的 post - 我 link 给你。

http://shipilev.net/blog/2014/safe-public-construction/

在你的例子中,因为你要返回子单例实例,我建议实例对象在子 class 中。另外,你可能想要更好的设计,考虑使用单例工厂。

简短的回答是,您不能覆盖静态方法,因为它们绑定到超类。

长话短说,这使得单例继承的实现变得复杂(假设您想在超类中保留实例)。参见 singleton and inheritance in Java