(4)单例模式

懒汉式与饿汉式讲解

https://blog.csdn.net/jiangshangchunjiezi/article/details/74597029

 

JDK中单例模式应用

    在JDK中java.lang.Runtime类,使用了饿汉式单例模式实现,保证了Runtime的唯一性。

源码如下:

 public class Runtime {
    private static Runtime currentRuntime = new Runtime();  //声明私有的静态类成员变量currentRuntime ,当类加载完成时,构造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() {}     //构造函数私有化,保证类外不可创建该类对象
 
......
 
 
 
}

饿汉式与懒汉式选择

饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不再改变 
懒汉式优点是延时加载、 是在需要的时候才创建对象。缺点是应该用同步。如果在创建实例对象时不 加上synchronized则会导致对对象的访问不是线程安全的。
推荐使用第一种。 

 

posted @ 2019-03-18 12:14  测试开发分享站  阅读(88)  评论(0编辑  收藏  举报