因为runtime类的方法都是与当前运行的jvm进程相关,要保证jvm中只有一个实例,所以用单例设计模式
如果你看一下runtime源代码,就知道它的构造函数被private修饰了,这像就不能对它再实例化了。这样设计应该是为了安全性考虑的。
这是它的源代码
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() {} |