單例設計模式是Java中應用最爲普遍的設計模式之一,保證了一個類始終只有一個對象,具備如下特色:java
這裏1有一個關於singleton的故事,一個國家只能有且僅有一個president,president只能被實例化一次,getPresident()返回這個僅有的president。設計模式
public class AmericaPresident { private static final AmericaPresident thePresident = new AmericaPresident(); private AmericaPresident() {} public static AmericaPresident getPresident() { return thePresident; } }
class Runtime { private static Runtime currentRuntime = new Runtime(); public static Runtime getRuntime() { return currentRuntime; } private Runtime() {} //... }