懒汉单例模式是指在需要使用对象实例时才创建该对象实例,而不是在类加载时就创建对象实例。以下是一种实现懒汉单例模式的方式:

public class LazySingleton {
    private static LazySingleton instance;

    private LazySingleton() {
        // 私有构造函数,防止外部实例化
    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }
}

在上述代码中,instance是单例对象的静态变量。getInstance()方法是获取单例对象的方法。在getInstance()方法中,首先检查instance是否为null,如果为null则进入同步块,再次检查instance是否为null,避免多线程竞争时重复创建对象。如果instancenull,则创建对象实例并赋值给instance。最后返回instance

请注意,上述实现方式在多线程环境下是安全的,因为使用了双重检查锁定(Double-Checked Locking)来保证只有在对象不存在时才进行同步创建

怎么实现懒汉单例后创建对象

原文地址: https://www.cveoy.top/t/topic/hQdd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录