设计模式之单例模式

本文深入探讨了单例模式的四种实现方式,包括饿汉式、双重检查锁定(DCL)、静态内部类和枚举,详细解释了每种方式的原理和应用场景,特别推荐使用静态内部类和枚举实现,因其利用了JVM的类加载机制,天然具备线程安全性。

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

使用场景:需要频繁的进行创建和销毁的对象,创建对象耗时较多或耗费资源过多(重量级对象),经常用到的对象,工具类对象,访问数据库或者文件对象(比如数据源,session工厂等)。

推荐使用以下四种方式:

1.饿汉式

如果可以确定肯定会使用的话,也可以使用,懒汉式容易出问题不太推荐。

class Singleton{
    private Singleton(){

    }
    private final static Singleton INSTANCE=new Singleton();

    public static Singleton getInstance(){
        return INSTANCE;
    }
}
class Singleton{
    private Singleton(){}
    static {
        INSTANCE=new Singleton();
    }
    private  static Singleton INSTANCE;
    public static Singleton getInstance(){
        return INSTANCE;
    }
}

2.dcl

class Singleton {
    private static volatile Singleton instance;
    private Singleton() { }
    public static Singleton getInstance() {
        if (instance == null) {
//            保证一个线程执行
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

3.静态内部类

//静态内部类推荐使用,运用jvm底层类装载的机制,保证线程安全
class Singleton {

    private Singleton() {
    }
    private static class SingletonInstance {
        private static final Singleton instance = new Singleton();
    }

    public static Singleton getInstance() {
        return SingletonInstance.instance;
    }
}

4.枚举

public class SingletonTest {
    public static void main(String[] args) {
        Singleton instance = Singleton.instance;
        Singleton instance1 = Singleton.instance;
        System.out.println(instance == instance1);
        System.out.println(instance.hashCode());
        System.out.println(instance1.hashCode());

    }
}

//枚举实现单例推荐使用
enum Singleton {
    instance;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值