必会手撸代码单例模式

本文详细介绍了单例模式的几种实现方式,包括饿汉模式、懒汉模式及其线程安全变体,并探讨了静态内部类方法作为懒汉模式的一种高效替代方案。

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

必会手撸代码

单例模式

饿汉模式

/**
 * 单列--饿汉式
 * 优点: 写法简单  缺点:如果该类未被使用,会一直存在 浪费内存空间
 * @Date: 2021/9/18 0018 下午 17:17
 * @Version: 1.0
 */
public class SingleHungry {

    private static SingleHungry single = new SingleHungry();

    private SingleHungry() {
    }

    private static SingleHungry getInstance(){
        return single;
    }
}

懒汉模式

/**
 * 单列--懒汉式
 * 优点: 需要使用过的时候创建  缺点:节约空间
 * @Date: 2021/9/18 0018 下午 17:17
 * @Version: 1.0
 */
public class SingleLazy {

    private static SingleLazy single;

    private SingleLazy() {
    }

    private static SingleLazy getInstance(){
        if (single == null){
            single = new SingleLazy();
        }
        return single;
    }
}

懒汉模式(线程安全、同步锁)

/**
 * 单列--懒汉式(线程安全)
 * 优点: 线程安全,同步执行
 * @Date: 2021/9/18 0018 下午 17:17
 * @Version: 1.0
 */
public class SingleSafe {

    private static SingleSafe single;

    private SingleSafe() {
    }

    private static SingleSafe getInstance(){
        if (single == null){
            synchronized (SingleSafe.class){
                single = new SingleSafe();
            }
        }
        return single;
    }
}

懒汉模式(双重线程)

/**
 * 单列--懒汉式(双重线程安全)
 * 优点: 线程安全,延迟加载
 * @Date: 2021/9/18 0018 下午 17:17
 * @Version: 1.0
 */
public class SingleDoubleSafe {

    private static SingleDoubleSafe single;

    private SingleDoubleSafe() {
    }

    private static SingleDoubleSafe getInstance(){
        if (single == null){
            synchronized (SingleDoubleSafe.class){
                if (single == null) {
                    single = new SingleDoubleSafe();
                }
            }
        }
        return single;
    }
}

双重线程的懒汉模式有替代方案也可以实现同样的方案(静态内部类)

/**
 * 静态内部类
 * @Description:
 * @Date: 2021/9/18 0018 下午 17:53
 * @Version: 1.0
 */
public class InsideClass {

    public InsideClass() {
    }

    private static class SingleInsideClass{
        static final InsideClass INSIDE_CLASS = new InsideClass();
    }

    public static InsideClass getInstance() {
        return SingleInsideClass.INSIDE_CLASS;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值