一尘不染

Java API中的单例类示例

java

Java API中Singleton设计模式的最佳示例是什么?是Runtime类单身?


阅读 179

收藏
2020-12-03

共1个答案

一尘不染

我想到的只有两个例子:

另请参阅


更新 :要回答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() {}

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

2020-12-03