Java API 中单例设计模式的最佳示例有哪些?是个Runtime
类单例?
我只想到两个例子:
- java.lang.Runtime#getRuntime() http://java.sun.com/javase/6/docs/api/java/lang/Runtime.html#getRuntime%28%29
- java.awt.Desktop#getDesktop() http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#getDesktop%28%29
See also:
- Java API 中 GoF 设计模式的真实示例 https://stackoverflow.com/questions/1673841/examples-of-gof-design-patterns/2707195#2707195
Update:要回答 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
构造函数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)