知道Runtime获取对象需要用getRuntime而不是用new,用了单例模式,可是当初的设计者为什么把他设计成这样子?
Runtime属于单例类,采用单例模式,不能new,只能通过方法获取对象。
单例类最重要的特点是构造方法私有化,这样在类得外部就不能构造和创建类得实例。下面是Runtime类的源码
通过源码,我们就可以看出它确实是单例类。
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;
}
……
}
Runtime属于单例类,采用单例模式,不能new,只能通过方法获取对象。
单例类最重要的特点是构造方法私有化,这样在类得外部就不能构造和创建类得实例。下面是Runtime类的源码
通过源码,我们就可以看出它确实是单例类。
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;
}
……
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货