代码实战-单例设计模式中的懒汉实现方式

DBC 2K 0
小例子
package net.xdclass;



public class SingletonLazy {


    private static SingletonLazy instance;

    /**
     * 构造函数私有化
     */
    private SingletonLazy(){}


    /**
     * 单例对象的方法
     */
    public void process(){
        System.out.println("方法调用成功");
    }

    /**
     * 第一种方式
     * 对外暴露一个方法获取类的对象
     *
     * 线程不安全,多线程下存在安全问题
     *
     */
//    public static SingletonLazy getInstance(){
//        if(instance == null){
//            instance = new SingletonLazy();
//        }
//        return instance;
//    }


    /**
     * 第二种实现方式
     *  通过加锁 synchronized 保证单例
     *
     * 采用synchronized 对方法加锁有很大的性能开销
     *
     * 解决办法:锁粒度不要这么大
     *
     * @return
     */
//    public static synchronized SingletonLazy getInstance(){
//        if(instance == null){
//            instance = new SingletonLazy();
//        }
//        return instance;
//    }


    /**
     * 第三种实现方式
     * @return
     */
    public static  SingletonLazy getInstance(){
        if(instance == null){
            // A、B
            synchronized (SingletonLazy.class){
                instance = new SingletonLazy();
            }
        }
        return instance;
    }



}
  SingletonLazy.getInstance().process();
控制台输出
代码实战-单例设计模式中的懒汉实现方式插图
温馨提示

依然不安全,继续看进阶文章!

发表评论 取消回复
表情 图片 链接 代码

分享