設計模式三 之 單例模式(Singleton)

單例模式(Singletonhtml

單例對象能保證在一個JVM中,該對象只有一個實例存在。java

寫法一:可是有可能會出現線程安全問題安全

public class Singleton {  
  
    /* 持有私有靜態實例,防止被引用,此處賦值爲null,目的是實現延遲加載 */  
    private static Singleton instance = null;  
  
    /* 私有構造方法,防止被實例化 */  
    private Singleton() {  
    }  
  
    /* 靜態工程方法,建立實例 */  
    public static Singleton getInstance() {  
        if (instance == null) {  
            instance = new Singleton();  
        }  
        return instance;  
    }  
  
    /* 若是該對象被用於序列化,能夠保證對象在序列化先後保持一致 */  
    public Object readResolve() {  
        return instance;  
    }  
}

寫法二:考慮到線程安全問題服務器

public class SingletonTest {  
  
    private static SingletonTest instance = null;  
  
    private SingletonTest() {  
    }  
  
    private static synchronized void syncInit() {  
        if (instance == null) {  
            instance = new SingletonTest();  
        }  
    }  
  
    public static SingletonTest getInstance() {  
        if (instance == null) {  
            syncInit();  
        }  
        return instance;  
    }  
}

 

省去了new操做符,下降了系統內存的使用頻率,減輕GC壓力。線程

有些類如交易所的核心交易引擎,控制着交易流程,若是該類能夠建立多個的話,系統徹底亂了。(好比一個軍隊出現了多個司令員同時指揮,確定會亂成一團),因此只有使用單例模式,才能保證核心交易服務器獨立控制整個流程。code

Reference:https://www.cnblogs.com/maowang1991/archive/2013/04/15/3023236.htmlhtm

相關文章
相關標籤/搜索