编辑:已回答-错误在于方法不是静态的
我使用了单例设计模式
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
// Private constructor prevents instantiation from other classes
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
我的问题是如何在另一个类中创建一个Singleton类的对象?
我尝试过:
Singleton singleton = new Singleton();
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context
正确的代码是什么?
谢谢, Spencer
getInstance()
中避免使用get
,因为这违反了JavaBean命名约定。另一种替代方法是instance()
。 - Basil Bourque