很久没发帖了,请教一下Runtime本身的设计问题

iaiti
Java领域优质创作者
博客专家认证
2013-04-14 09:21:26
知道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;
}
……
}
...全文
115 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
摆烂办不到 2013-04-15
  • 打赏
  • 举报
回复
噢,原来如此,如果是new的话就有多个Runtime了
huntor 2013-04-14
  • 打赏
  • 举报
回复
一个正在运行的JRE只有一个运行时Runtime
STEEL-CHINA 2013-04-14
  • 打赏
  • 举报
回复
出发点是保证同一时刻只有一个exec执行。

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧