单例模式的四种写法

本文深入探讨了单例模式的各种实现方式,包括懒汉式(线程安全与不安全)、饿汉式、双重校验锁及静态内部类。每种方式都附有代码示例,详细分析了它们的优缺点,如线程安全性、懒加载特性及其对性能的影响。

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

懒汉式(线程不安全)

//懒汉式(线程不安全)
public class Singleton {
    private static Singleton singleton;
    private Singleton(){}

    private static Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}
//改进一下,懒汉式(线程安全)
public class Singleton {
    private static Singleton singleton;
    private Singleton(){}

    private static synchronized Singleton getInstance(){
        if(singleton == null){
            singleton = new Singleton();
        }
        return singleton;
    }
}

饿汉式(线程安全,但是不能实现懒加载的效果)

//饿汉式(但是没有懒加载效果)
public class Singleton{
    private static Singleton singleton = new Singleton();
    private Singleton(){}
    public static Singleton getInstance(){
        return singleton;
    }
}

双重校验锁(线程安全,有一定的性能损失)

//双重检查模式(有一定的性能损失)
public class Singleton{
    private static volatile Singleton singleton;
    private Singleton(){}
    public static Singleton getInstance(){
        if (singleton == null){
            synchronized(Singleton.class){
                if (singleton == null){
                    singleton = new Singleton();
                }
            }
        }
        return singleton;
    }
}

静态内部类(线程安全,并且能够实现懒加载效果)

//静态内部类(推荐)
public class Singleton{
    private Singleton(){}
    public static Singleton getInstance(){
        return innerclass.singleton;
    }
    private static class innerclass{
        private static final Singleton singleton = new Singleton();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值