單例模式(Singleton Pattern)

單例模式:函數

  和new相似,用來建立實例。spa

  單例對象的類保證了只有一個實例存在。code

 

原理:orm

  一、該類的構造函數定義爲私有方法,這樣外面不能經過new實例化此類,只能在類裏面實例化對象

  二、類返回一個獲取實例的方法blog

 

構建方式:get

  懶漢方式:全局的單例實例在第一次被使用是建立it

  餓漢方式:全局的單例實例在類裝載時構建io

 

維基百科code例子:form

餓漢方式建立:

  public class Singleton {
    private static final Singleton INSTANCE = new Singleton();
  
    // Private constructor suppresses   
    private Singleton() {}
 
    // default public constructor
    public static Singleton getInstance() {
        return INSTANCE;
    }
  }

 

懶漢方式建立:

  public class Singleton {
    private static volatile Singleton INSTANCE = null;
  
    // Private constructor suppresses 
    // default public constructor
    private Singleton() {}
  
    //thread safe and performance  promote 
    public static  Singleton getInstance() {
        if(INSTANCE == null){
             synchronized(Singleton.class){
                 //when more than two threads run into the first null check same time, to avoid instanced more than one time, it needs to be checked again.
                 if(INSTANCE == null){ 
                     INSTANCE = new Singleton();
                  }
              } 
        }
        return INSTANCE;
    }
  }
相關文章
相關標籤/搜索