单例模式的写法?

发布于:2024-08-02 ⋅ 阅读:(113) ⋅ 点赞:(0)

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

1. 饿汉式(Eager Initialization)

public class Singleton {
    // 创建唯一实例
    private static final Singleton INSTANCE = new Singleton();
    
    // 私有构造函数,防止外部创建多个实例
    private Singleton() {}
    
    // 提供全局访问点
    public static Singleton getInstance() {
        return INSTANCE;
    }
}

2. 懒汉式(Lazy Initialization)

public class Singleton {
    // 延迟实例化
    private static Singleton instance;
    
    // 私有构造函数
    private Singleton() {}
    
    // 提供全局访问点,双重检查锁定实现线程安全
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

3. 双重检查锁定(Double-Checked Locking)

public class Singleton {
    // 使用volatile关键字保证内存可见性
    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;
    }
}

4. 静态内部类(Bill Pugh Singleton Design)

public class Singleton {
    // 静态内部类
    private static class SingletonHolder {
        private static final Singleton INSTANCE = new Singleton();
    }
    
    // 私有构造函数
    private Singleton() {}
    
    // 提供全局访问点
    public static Singleton getInstance() {
        return SingletonHolder.INSTANCE;
    }
}

5. 枚举实现(Effective Java推荐)

public enum Singleton {
    INSTANCE;
    
    // 可以添加其他方法和属性
    public void someMethod() {
        // 实现方法
    }
}

每种实现方式有其优缺点。一般来说,静态内部类和枚举实现被认为是最简洁且线程安全的方式。