【发布时间】:2014-02-06 13:22:57
【问题描述】:
我有两个版本的“Initialization-on-demand holder idiom”:
- http://en.wikipedia.org/wiki/Initialization-on-demand_holder_idiom
- http://en.wikipedia.org/wiki/Singleton_pattern#The_solution_of_Bill_Pugh
上面的主要区别是第一个声明INSTANCE为private,而第二个声明INSTANCE为public。
请告诉我应该使用哪一个。
抱歉,我没有发现在我的应用程序中使用 private 和 public 之间的区别:
public class Singleton {
private int x;
public int getX() {
return x;
}
private Singleton () {}
private static class LazyHolder {
//both private and public works
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
我唯一要做的就是打电话给Singleton.getInsance().getX(),所以两个版本都可以。
因此我想知道使用它们的情况。
【问题讨论】:
标签: java design-patterns concurrency