Spring单例模式实现的几种方式

一、懒汉式

1.懒汉式-非线程安全版

public class LazySingletonClass {
    private static LazySingletonClass instance = null;
    private LazySingletonClass(){
        
    }
    public static LazySingletonClass getInstance(){
        if (instance == null){
            instance = new LazySingletonClass();
        }
        return instance;
    }
}

2.懒汉式-线程安全

public class LazySingletonClass {
    private static LazySingletonClass instance = null;
    private LazySingletonClass(){

    }
    public static synchronized LazySingletonClass getInstance(){
        if (instance == null){
            instance = new LazySingletonClass();
        }
        return instance;
    }
}

二、饿汉式

public class HungerSingletonClass {
    private static HungerSingletonClass instance = new HungerSingletonClass();
    private HungerSingletonClass(){
        
    }
    
    public static HungerSingletonClass getInstance(){
        return instance;
    }
}

三、双检锁/双重校验锁(DCL,即 double-checked locking)

public class DoubleLockSingletonClass {
    private static DoubleLockSingletonClass instance;

    private DoubleLockSingletonClass() {

    }

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

四、登记式/静态内部类

public class HolderSingletonClass {
    private static class SingletonHolder {
        private static HolderSingletonClass INSTANCE = new HolderSingletonClass();
    }

    private HolderSingletonClass() {

    }

    public static HolderSingletonClass getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值