對於單例模式的理解

 //餓漢式
 //簡單的單例模式,線程安全,可是性能低, 當singletontest被建立的時候 會被實例化 佔用內存
public class SingletonTest(){
   //構造函數私有化
   private SingletonTest(){}

   private static final SingletonTest instance = new SingletonTest();
   private static SingletonTest getInstance(){
      return instance;
}
}
 //懶漢式 
 //線程不安全 調用getInstance的時候可能屢次實例化
public class SingletonTest{
   //構造函數私有化
   private SingletonTest(){}
   private static SingletonTest instance;
   private static SingletonTest getInstance()[
      if(instance==null){
         instance = new SingletonTest();
      }
      return instance;
   }
}

 //簡單優化
 //線程安全,可是性能低,被加了 synchronized
public class SingletonTest{
   //構造函數私有化
   private SingletonTest(){}
   private static SingletonTest instance;
   private static synchronized SingletonTest getInstance()[
      if(instance==null){
         instance = new SingletonTest();
      }
      return instance;
   }
}
 //最優方案
public class SingletonTest{
   //構造函數私有化
   private SingletonTest(){}
   private static SingletonTest instance;
   private static SingletonTest getInstance()[
      if(instance==null){
    //同步代碼塊
         synchronized(SingletonTest.class){
            if(instance==null){
               instance = new SingletonTest();
            }
         }
      }
      return instance;
   }
}
相關文章
相關標籤/搜索