单例模式(Singleton Pattern)是一种设计模式,确保一个类只有一个实例,并提供一个全局访问点。下面是保证线程安全的单例模式的几种常见实现方式:
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 方法时都需要加锁。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; } }
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 类,避免了饿汉式的资源浪费。public enum Singleton { INSTANCE; // 可以添加其他方法和字段 public void someMethod() { // 实现 } }
上一篇:Apache Drill:大数据的实时SQL查询引擎
下一篇:介绍rabbitMQ