java API中的单例类
Java API中Singleton Pattern的最佳示例是什么? Runtime类是单例吗?
只有两个例子浮现在脑海中:
java.lang.Runtime#getRuntime()
-
java.awt.Desktop#getDesktop()
另见 :
- Java API中GoF设计模式的真实示例
更新 :回答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
Runtime
are instance * methods and must be invoked with respect to the current runtime object. * * @return theRuntime
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
为什么单身人士是邪恶的
我过去曾经用过它们,看到了一些好处。 当我试图与他们一起进行测试驱动开发时,我也非常生气,因为他们是邪恶的一个领域。 同样inheritance它们导致一些难以理解的行为 – 至少在Python中 – 我不确定在Java中。 一般来说,你只是因为这个而不这样做。 所以像线程一样,这些看起来好像是一个好主意然后你遇到了陷阱并且意识到这可能毕竟不是那么好。
这适用于Swing: SingleFrameApplication 。 看看这个演示文稿,它精彩地描述了它是如何工作的。