Java - 设计模式之单例模式(懒汉式 V2)

synchronized:结果正确,但是会带来性能的开销,不推荐

package com.mmall.concurrency.example.singleton;

import com.mmall.concurrency.annoations.NotRecommend;
import com.mmall.concurrency.annoations.ThreadSafe;

/**
 * 懒汉模式
 * 单例实例在第一次使用时进行创建
 */
@ThreadSafe
@NotRecommend
public class SingletonExample3 {

    // 私有构造函数
    private SingletonExample3() {

    }

    // 单例对象
    private static SingletonExample3 instance = null;

    // 静态的工厂方法
    public static synchronized SingletonExample3 getInstance() {
        if (instance == null) {
            instance = new SingletonExample3();
        }
        return instance;
    }
}
发布了1003 篇原创文章 · 获赞 1884 · 访问量 89万+

猜你喜欢

转载自blog.csdn.net/Dream_Weave/article/details/105506935