单例模式全总结

本文详细探讨了单例模式的多种实现方式,包括饿汉式、懒汉式、内部类和枚举类等,对比了它们在并发安全性、效率及可见性上的优缺点。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.饿汉式 类加载机制保证单例 无并发问题

public class HungrySingleton {
    private static  HungrySingleton singleton = new HungrySingleton();

    private HungrySingleton(){}

    public static HungrySingleton getSingleton(){
        return singleton;
    }

}

2.饿汉式

//第一种饿汉式   效率高 使用时加载线程不安全
public class LazySingleton {
    private static  LazySingleton singleton=null;
    private LazySingleton(){
    }

    public static LazySingleton getSingleton(){
        if (singleton == null){
            singleton = new LazySingleton();
        }
        return singleton;
    }

}
//懒汉式2  线程安全 效率低 使用时加载
public class LazySingleton1 {
    private static LazySingleton1 singleton = null;

    private LazySingleton1(){}

    public synchronized static LazySingleton1 getSingleton() {
        if (singleton == null){
            singleton = new LazySingleton1();
        }
        return singleton;
    }
}
//懒汉式  效率高  使用时加载 有可见性问题
public class LazySingleton2 {
    private static LazySingleton2 singleton = null;

    private LazySingleton2(){}

    public static LazySingleton2 getSingleton() {
        if (singleton ==null){
            synchronized(LazySingleton2.class){
                if (singleton == null){
                    singleton = new LazySingleton2();
                }
            }
        }
        return singleton;
    }
}
//懒汉四 双端检索机制+volatile 效率高 安全  使用时加载
public class LazySingleton3 {

    private static volatile LazySingleton3 singleton = null;

    private LazySingleton3(){}

    public static LazySingleton3 getSingleton(){
        if (singleton == null){
            synchronized (LazySingleton3.class){
                if (singleton == null){
                    singleton = new LazySingleton3();
                }
            }
        }
        return singleton;
    }
}

3.内部类方式

//内部类方式
public class InnerClassSingleton {

    private InnerClassSingleton(){}
    private static class Singleton {
        private static InnerClassSingleton singleton = new InnerClassSingleton();
    }

    public static InnerClassSingleton getSingleton(){
        return Singleton.singleton;
    }
}

4.枚举类方式

//枚举类方式  高效 真正保证系统中该对象的单例属性  其他单例模式可能再序列化和反序列化的机制下不能保证单例
public enum  EnumSingleton {
    SINGLETON;

    private EnumSingleton(){}

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值