Runtime源码分析 - 单例设计模式
发布日期:2021-06-30 16:57:27 浏览次数:2 分类:技术文章

本文共 2508 字,大约阅读时间需要 8 分钟。

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 Runtime are instance * methods and must be invoked with respect to the current runtime object. * * @return the Runtime object associated with the current * Java application. */ public static Runtime getRuntime() {
return currentRuntime; } /** Don't let anyone else instantiate this class */ private Runtime() {
}}

g o o g l e \color{#4285f4}{g}\color{#ea4335}{o}\color{#fbbc05}{o}\color{#4285f4}{g}\color{#34a853}{l}\color{#ea4335}{e} google

分析

  • 先看构造
/** Don't let anyone else instantiate this class */    private Runtime() {
}

构造设为private,无法调用new对象。

  • 在看如何获取对象

用 public static 的方法 g e t R u n t i m e ( ) \color{#ea4335}{getRuntime()} getRuntime(),可以通过静态调用获得对象。

/**     * Returns the runtime object associated with the current Java application.     * Most of the methods of class Runtime are instance     * methods and must be invoked with respect to the current runtime object.     *     * @return  the Runtime object associated with the current     *          Java application.     */    public static Runtime getRuntime() {
return currentRuntime; }
  • 最后,看单例的来源
private static Runtime currentRuntime = new Runtime();

在类初始化时候new一次对象,用 c u r r e n t R u n t i m e \color{#4285f4}{currentRuntime} currentRuntime引用。

确保了,对象唯一,即“单例”
其中:
private 确保 c u r r e n t R u n t i m e \color{#4285f4}{currentRuntime} currentRuntime不被随意修改。
static 确保能被 g e t R u n t i m e ( ) \color{#ea4335}{getRuntime()} getRuntime()方法调用

饿汉式 or 懒汉式

上述方法为“饿汉式”,即在类初始化时候就 new 出唯一的对象。

还有一种“懒汉式”,即在调用 g e t R u n t i m e ( ) \color{#ea4335}{getRuntime()} 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 Runtime are instance * methods and must be invoked with respect to the current runtime object. * * @return the Runtime 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() {
}}

转载地址:https://lawsssscat.blog.csdn.net/article/details/103012982 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!

上一篇:Java培优班-第八天 - JavaSE -(面向对象)
下一篇:《数据结构与算法分析-java语言描述》 - 表达式树 -后缀表达式录入成表达式树

发表评论

最新留言

关注你微信了!
[***.104.42.241]2024年04月22日 15时57分49秒