第一种(懒汉,线程不安全):

1 public class Singleton {
2     private static Singleton instance;
3     private Singleton (){}
4     public static Singleton getInstance() {
5     if (instance == null) {
6         instance = new Singleton();
7     }
8     return instance;
9     }
10 }

  这种写法lazy loading很明显,但是致命的是在多线程不能正常工作。
 

  第二种(懒汉,线程安全):

1     public class Singleton {
2     private static Singleton instance;
3     private Singleton (){}
4     public static synchronized Singleton getInstance() {
5     if (instance == null) {
6         instance = new Singleton();
7     }
8     return instance;
9     }
10   }
11

  这种写法能够在多线程中很好的工作,而且看起来它也具备很好的lazy loading,但是,遗憾的是,效率很低,99%情况下不需要同步。
 

  第三种(饿汉):.
``````````````````````````````````````````````````
    这种方式基于classloder机制避免了多线程的同步问题,不过,instance在类装载时实例化,虽然导致类装载的原因有很多种,在单例模式中大多数都是调用getInstance方法, 但是也不能确定有其他的方式(或者其他的静态方法)导致类装载,这时候初始化instance显然没有达到lazy loading的效果。
 

  第四种(饿汉,变种):

1 public class Singleton {
2     private Singleton instance = null;
3     static {
4     instance = new Singleton();
5     }
6     private Singleton (){}
7     public static Singleton getInstance() {
8     return this.instance;
9     }
10 }

  表面上看起来差别挺大,其实更第三种方式差不多,都是在类初始化即实例化instance。