Singleton的三種方案

一、//Synchronize the method public class Singleton {

    private static Singleton uniqueInstantce;

    private Singleton() {     }

    public static synchronized Singleton getInstance() {  if (uniqueInstantce == null) {      uniqueInstantce = new Singleton();  }  return uniqueInstantce;     } }

會大大降低程序的性能

二、//Use eager instantiation public class Singleton2 {

    private static Singleton2 uniqueInstantce = new Singleton2();

    private Singleton2() {     }

    public static Singleton2 getInstance() {  return uniqueInstantce;     } }

三、//Double-checked locking public class Singleton3 {

    private volatile static Singleton3 uniqueInstantce;

    private Singleton3() {     }

    public static Singleton3 getInstance() {  if (uniqueInstantce == null) {      synchronized (Singleton3.class) {   if (uniqueInstantce == null) {       uniqueInstantce = new Singleton3();   }      }  }  return uniqueInstantce;     } }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章