java設計模式之單例模式

public class Singleton {
    //私有的 靜態的 本類屬性
    private volatile static Singleton _instance;
    //私有化構造器
    private Singleton() {}
     /*
      * 懶漢模式
      */
     public static Singleton getInstance() {
         if (_instance == null) {
             _instance = new Singleton();
         }
         return _instance;
     }
  
    /*
     *2 synchronized版本
     */
 
    public static synchronized Singleton getInstanceTS() {
        if (_instance == null) {
            _instance = new Singleton();
        }
        return _instance;
    }
  
    //3.雙重檢查鎖:檢查了2次;使用了一個鎖
    //此處需要volatile修飾屬性保證它的內存可見性??
     public static Singleton getInstanceDC() {
         if (_instance == null) {//第一次檢查
             synchronized (Singleton.class) {
                 if (_instance == null) { //第二次檢查   //線程1創建完對象後,線程會判斷一次就不會創建對象了。解決了首次創建對象的唯一性問題。
                     _instance = new Singleton();
                 }
             }
         }
         return _instance;
     }
 }

轉:https://www.cnblogs.com/paul011/p/8574650.html

根據內部類不會在其外部類被加載的同時被加載的事實,我們可以引申出單例模式的一種實現方式: 靜態內部類

Java代碼  

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

    該“靜態內部類”實現單例模式的方式,在單例對象佔用資源大,需要延時加載的情況下優選。

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