Java - 无法在静态类中声明对象

标签 java singleton static-methods

我正在尝试为系统类实现单例模式。我发现的示例无法编译(例如 http://www.tutorialspoint.com/java/java_using_singleton.htm )。非静态类中有一个静态方法。因此,我将类设为静态,一切都很顺利,直到我尝试为 Timer 类创建一个成员变量。

现在我收到消息“没有可访问的 scene_3d 类型的封闭实例。必须用封闭实例限定分配...

我四处寻找,但没有人为我编译单例模式。顺便说一下,我正在使用Processing(一个Java IDE/扩展)。任何有关如何解决此问题的想法都会有很大帮助。谢谢!

static public class DemoSystem {
  private static DemoSystem instance = null;  
  protected DemoSystem() {}

  public static DemoSystem Inst() {
    if( instance == null ) {
      instance = new DemoSystem();
    }
    return instance;
  }

  void init() {
    Timer timer = new Timer();  
  }

  int getTime() {
    return timer.elapsedTime;
  }
}

最佳答案

标准的单例模式是有一个私有(private)构造函数和一个静态实例变量,所以:

public class DemoSystem {
  private static DemoSystem instance = null;
  private Timer timer;
  protected DemoSystem() {}

  public static DemoSystem Inst() {
    if( instance == null ) {
      instance = new DemoSystem();
    }
    return instance;
  }

  void init() {
    timer = new Timer();  
  }

  int getTime() {
    return timer.elapsedTime;
  }
}

修复导入后,这应该可以正常工作。

关于Java - 无法在静态类中声明对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14847659/

相关文章:

java - 如何从捆绑了 Maven 依赖项的 Eclipse 中导出完整的 war 文件?

c++ - cuda调用在析构函数中失败

c++ - 类中的静态内联函数

c# - 有没有办法从静态方法调用非静态方法?

c++ - 从单例类中删除对象

java 在静态方法和主方法中处理变量声明和初始化

java - JTextPane 滚动到特定行

java - 如何将 Dimension 值转换为字符串或整数

java - 如何在java中将两个大数(比如512位)相乘

c++ - 有人可以确认这是否是单例的线程安全实现吗