Java API中的单例类的示例

时间:2010-06-17 11:46:31

标签: java design-patterns

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

3 个答案:

答案 0 :(得分:11)

只想到两个例子:

另见


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

答案 1 :(得分:0)

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

Singleton Wiki Article

Java Dev on Singletons

Why Singletons are Evil

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

答案 2 :(得分:-1)

这适用于Swing:SingleFrameApplication。查看this presentation它精彩地描述了它是如何工作的。

相关问题