我正在尝试为系统类实现单例模式。我发现的示例无法编译(例如 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/