方式一:
public class Singleton {
private Singleton() {
}
private static class LazyHolder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return LazyHolder.INSTANCE;
}
}
一般而言,这种方式见得最多的写法是static final,那么final是否是必须的呢?
多个线程调用静态方法getInstance()时,JVM也只会加载和初始化内部类一次,将静态变量INSTANCE定义不可变的final是否必须?
在wikipedia的页面中,采取的是方式一:Initialization-on-demand holder idiom
怪我咯2017-04-18 10:35:52
After adding final, it becomes mutable. There is no other difference.
A better approach for Singleton is to use Enum (see Effective Java for details).
阿神2017-04-18 10:35:52
No difference, declare private
,其它类也无法直接访问(反射除外)。如果担心反射访问,就如楼上说的用Enum
to create a singleton.