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;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
}
分析
- <mark>先看构造</mark>:
/** Don't let anyone else instantiate this class */
private Runtime() {}
构造设为private,无法调用new对象。
- <mark>在看如何获取对象</mark>:
用 public static 的方法 getRuntime(),可以通过静态调用获得对象。
/** * 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;
}
- <mark>最后,看单例的来源</mark>:
private static Runtime currentRuntime = new Runtime();
在类初始化时候new一次对象,用 currentRuntime引用。
<mark>确保了,对象唯一,即“单例”</mark>
其中:
private 确保 currentRuntime不被随意修改。
static 确保能被 getRuntime()方法调用
饿汉式 or 懒汉式
上述方法为“饿汉式”,即在类初始化时候就 new 出唯一的对象。
还有一种“懒汉式”,即在调用 getRuntime()方法的时候才 new 出唯一的对象。
只需要稍微改下上面代码即可变为“懒汉式”。
public class Runtime {
private static Runtime currentRuntime = null;
/** * 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() {
if(currentRuntime == null){
currentRuntime = new Runtime();
}
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
}