【Java】單例(singleton)設計模式

單例設計模式是Java中應用最爲普遍的設計模式之一,保證了一個類始終只有一個對象,具備如下特色:java

  • 私有的構造函數 ——沒有其餘的類能實例化該對象
  • 引用時私有的
  • public static方法是獲取對象的惟一方式

singleton故事

這裏1有一個關於singleton的故事,一個國家只能有且僅有一個president,president只能被實例化一次,getPresident()返回這個僅有的president。設計模式

public class AmericaPresident {
    private static final AmericaPresident thePresident = new AmericaPresident();

    private AmericaPresident() {}

    public static AmericaPresident getPresident() {
        return thePresident;
    }
}

singleton在runtime中的應用

class Runtime {
    private static Runtime currentRuntime = new Runtime();

    public static Runtime getRuntime() {
        return currentRuntime;
    }

    private Runtime() {}

    //... 
}
相關文章
相關標籤/搜索