Java API中的单例类的示例

Jav*_*ser 9 java design-patterns

Java API中Singleton设计模式的最佳示例是什么?这个Runtime班是一个单身人士吗?

Bal*_*usC 12

只有两个例子浮现在脑海中:

另见:


更新:回答PeterMmm的(目前已删除?)评论(询问我是如何知道它是单例),检查javadoc和源代码:

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

    /**
     * Returns the runtime object associated with the current Java application.
     * Most of the methods of class <code>Runtime</code> are instance 
     * methods and must be invoked with respect to the current runtime object. 
     * 
     * @return  the <code>Runtime</code> object associated with the current
     *          Java application.
     */
    public static Runtime getRuntime() { 
        return currentRuntime;
    }

    /** Don't let anyone else instantiate this class */
    private Runtime() {}
Run Code Online (Sandbox Code Playgroud)

它每次都返回相同的实例,并且它有一个private构造函数.