本文介绍了Java API中的单例类示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Java API中Singleton设计模式的最佳示例是什么? Runtime
类是单例吗?
What are the best examples of the Singleton design pattern in the Java APIs? Is the Runtime
class a singleton?
推荐答案
只有两个例子注意:
java.lang.Runtime#getRuntime()
java.awt.Desktop#getDesktop()
请参见也:
- Real world examples of GoF Design Patterns in Java API
更新:要回答PeterMmm(当前已删除?)的评论(问我如何知道这是一个单例),请检查javadoc和源代码:
Update: to answer PeterMmm's (currently deleted?) comment (which asked how I knew that it was a singleton), check the javadoc and source code:
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
构造函数。
It returns the same instance everytime and it has a private
constructor.
这篇关于Java API中的单例类示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!