繁体   English   中英

Java API中的单例类的示例

[英]Examples of singleton classes in the Java APIs

Java API中Singleton设计模式的最佳示例是什么? 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构造函数。

注意单身人士应谨慎使用和反思。 在实施单身人士之前,请考虑反对单身人士和你的情况。 过度使用单例是一种反模式 - 类似于全局变量。

Singleton Wiki文章

单身人士的Java Dev

为什么单身人士是邪恶的

我过去曾经使用它们,看到它们有一些好处。 当我试图与他们一起进行测试驱动开发时,我也非常生气,因为他们是邪恶的一个领域。 同样继承它们会导致一些难以理解的行为 - 至少在Python中 - 我不确定在Java中。 一般来说,你只是因为这个而不这样做。 所以像线程一样,这些看起来好像是一个好主意然后你遇到了陷阱并且意识到这可能毕竟不是那么好。

这适用于Swing: SingleFrameApplication 看看这个演示文稿,它精彩地描述了它是如何工作的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM