public class Singleton {private static final Singleton INSTANCE = new Singleton();private Singleton() {}public static Singleton getInstance() {return INSTANCE;}}
这种实现方式有几个特点:
实例一开始就被创建(Eager initialization)。
getInstance()方法不需要加synchronize来解决多线程同步的问题。
final关键字确保了实例不可变,并且只会存在一个。
1)Lazy initialization
懒加载的方式使得单例会在第一次使用到时才会被创建.先看一种有隐患的写法:
12345678910111213141516
public final class LazySingleton {private static volatile LazySingleton instance = null;// private constructorprivate LazySingleton() {}public static LazySingleton getInstance() {if (instance == null) {synchronized (LazySingleton.class) {instance = new LazySingleton();}}return instance;}}
University of Maryland Computer Science researcher Bill Pugh有写过一篇文章initialization on demand holder idiom。
12345678910111213141516
public class Singleton {// Private constructor prevents instantiation from other classesprivate Singleton() { }/** * SingletonHolder is loaded on the first execution of Singleton.getInstance() * or the first access to SingletonHolder.INSTANCE, not before. */private static class SingletonHolder {public static final Singleton INSTANCE = new Singleton();}public static Singleton getInstance() {return SingletonHolder.INSTANCE;}}