【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() {}

    //... 
}
相关文章
相关标签/搜索