【发布时间】:2010-05-14 06:42:03
【问题描述】:
编辑:已回答 - 错误是方法不是静态的
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;
}
}
我的问题是如何在 another 类中创建 Singleton 类的对象?
我试过了:
Singleton singleton = new Singleton();
// error - constructor is private
Singleton singleton = Singleton.getInstance();
// error - non-static method cannot be referenced from a static context
什么是正确的代码?
谢谢, 斯宾塞
【问题讨论】:
-
仅供参考,有些人在
getInstance()中避免使用get,因为JavaBean naming convention 用于属性。另一种选择是instance()。
标签: java design-patterns singleton initialization