java - Java API 中单例类的示例

标签 java design-patterns

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

最佳答案

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

另见:


更新:回答 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 构造函数。

关于java - Java API 中单例类的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3061328/

相关文章:

java - 使用策略模式避免向下转型

c# - 查看模型和依赖注入(inject)

design-patterns - Dart 中匿名类的替换模式

java - 数据对象应该被认为是不可变的吗?

java - 尝试连接到 DB2 服务器时出错

java - 打包的 Spring boot 应用程序无法将其余 api 错误解析为消息

java - 传递同一类的另一个实例并将其存储的值与当前存储的值进行比较

java - 具有多个Windows设计的MVC

c# - 在现有模型对象之上实例化 ViewModels 和 Views

java - 为什么我得到了错误的列表?