简体   繁体   English

Java API中的单例类的示例

[英]Examples of singleton classes in the Java APIs

What are the best examples of the Singleton design pattern in the Java APIs? Java API中Singleton设计模式的最佳示例是什么? Is the Runtime class a singleton? Runtime类是单例吗?

Only two examples comes to mind: 只有两个例子浮现在脑海中:

See also : 另见


Update : to answer PeterMmm's (currently deleted?) comment (which asked how I knew that it was a singleton), check the javadoc and source code: 更新 :回答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() {}

It returns the same instance everytime and it has a private constructor. 它每次都返回相同的实例,并且它有一个private构造函数。

Note singletons should be used with care and reflection. 注意单身人士应谨慎使用和反思。 Consider the arguments against singletons and your situation before you implement one. 在实施单身人士之前,请考虑反对单身人士和你的情况。 Overuse of singletons is an anti-pattern - similar to global variables. 过度使用单例是一种反模式 - 类似于全局变量。

Singleton Wiki Article Singleton Wiki文章

Java Dev on Singletons 单身人士的Java Dev

Why Singletons are Evil 为什么单身人士是邪恶的

I've used them in the past and see some benefit to them. 我过去曾经使用它们,看到它们有一些好处。 I've also been highly annoyed when trying to do test driven development with them around that's one area where they are evil. 当我试图与他们一起进行测试驱动开发时,我也非常生气,因为他们是邪恶的一个领域。 Also inheriting from them results in some hard to understand behaviour - at least in Python - I don't know for sure in Java. 同样继承它们会导致一些难以理解的行为 - 至少在Python中 - 我不确定在Java中。 Generally you just don't do it because of that. 一般来说,你只是因为这个而不这样做。 So like threading these seem like a great idea at first and then you run into the pitfalls and realize well maybe this isn't so good after all. 所以像线程一样,这些看起来好像是一个好主意然后你遇到了陷阱并且意识到这可能毕竟不是那么好。

This is for Swing : SingleFrameApplication . 这适用于Swing: SingleFrameApplication Check out this presentation it wonderfully describes how does it work. 看看这个演示文稿,它精彩地描述了它是如何工作的。

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

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