单例的实现方式

单例模式确保一个类只有一个实例,并提供一个全局访问点。以下是几种常见的单例模式实现方式,主要以Java语言为例:

1. 饿汉式(静态初始化)


这是最简单的实现方式,类加载时就完成了初始化,保证线程安全。

public class Singleton {
    private static final Singleton INSTANCE = new Singleton();

    private Singleton() {}

    public static Singleton getInstance() {
        return INSTANCE;
    }
}


 

 2. 懒汉式(线程不安全)


实现懒加载,即在第一次使用时才创建实例,但未处理多线程并发问题。

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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


 

3. 同步方法(懒汉式,线程安全)


通过在获取实例的方法上加锁,确保线程安全,但每次访问都需同步,影响性能。
 

public class Singleton {
    private static Singleton instance;

    private Singleton() {}

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

 4. 双重检查锁定(DCL)


在多线程环境下,既能确保线程安全,又能保证高效地懒加载实例。

public 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;
    }
}


 

 5. 静态内部类


利用Java类加载机制保证初始化实例时的线程安全,同时也实现了懒加载。

public class Singleton {
    private Singleton() {}

    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

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


 

 6. 枚举(Effective Java推荐)
使用枚举实现单例,线程安全且序列化友好。

public enum Singleton {
    INSTANCE;

    // 可以在这里添加实例方法
}


 

每种方式都有其适用场景,开发者应根据实际需求选择最适合的实现方式。在大多数情况下,推荐使用双重检查锁定或静态内部类方式,因为它们既保证了线程安全,又实现了懒加载,且具有较高的性能。

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值