您的位置:首页 > 财经 > 产业 > 单例模式(java)

单例模式(java)

2024/10/5 16:29:45 来源:https://blog.csdn.net/2301_79075954/article/details/141001273  浏览:    关键词:单例模式(java)

单例模式(Singleton Pattern)是一种设计模式,确保一个类只有一个实例,并提供一个全局访问点。下面是保证线程安全的单例模式的几种常见实现方式:

1. 懒汉式(线程安全的双重检查锁定)

public class Singleton {private static volatile Singleton instance;private Singleton() {// 防止反射攻击if (instance != null) {throw new IllegalStateException("Instance already created.");}}public static Singleton getInstance() {if (instance == null) {synchronized (Singleton.class) {if (instance == null) {instance = new Singleton();}}}return instance;}
}

 

  • volatile 关键字用于确保在多线程环境下,instance 变量的可见性。
  • 双重检查锁定:先检查实例是否存在,如果不存在才加锁,再检查一次是否存在,从而避免了每次调用 getInstance 方法时都需要加锁。

2. 饿汉式(静态常量)

public class Singleton {private static final Singleton instance = new Singleton();private Singleton() {// 防止反射攻击if (instance != null) {throw new IllegalStateException("Instance already created.");}}public static Singleton getInstance() {return instance;}
}
  • 饿汉式在类加载时创建实例,线程安全,但可能在未使用时浪费资源。

3. 静态内部类(推荐)

public class Singleton {private Singleton() {// 防止反射攻击if (InstanceHolder.INSTANCE != null) {throw new IllegalStateException("Instance already created.");}}private static class InstanceHolder {private static final Singleton INSTANCE = new Singleton();}public static Singleton getInstance() {return InstanceHolder.INSTANCE;}
}
  • 静态内部类利用类加载机制来保证线程安全,并且只有在真正需要时才会加载 InstanceHolder 类,避免了饿汉式的资源浪费。

4. 枚举单例(最简单且线程安全)

public enum Singleton {INSTANCE;// 可以添加其他方法和字段public void someMethod() {// 实现}
}
  • 枚举单例是最简单且线程安全的单例实现方式,避免了多线程问题和反射攻击。

 

 

 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com