单例模式

定义

单例模式(Singleton Pattern)是一种创建型设计模式,确保一个类只有一个实例,并提供一个全局访问点。

核心特性

  1. 唯一性:保证一个类只有一个实例存在
  2. 全局访问:提供全局访问该实例的方法
  3. 延迟初始化:通常在第一次被请求时才创建实例(懒汉式)

实现方式

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 volatile static Singleton instance;
    
    private Singleton() {}
    
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}

  • 减少同步块的使用,提高性能
  • 需要volatile防止指令重排序

5. 静态内部类

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

  • 线程安全
  • 延迟加载
  • 实现简单

6. 枚举实现

public enum Singleton {
    INSTANCE;
    
    public void doSomething() {
        // ...
    }
}

  • 简洁
  • 自动支持序列化机制
  • 绝对防止多次实例化
  • 最安全的单例实现方式

应用场景

  1. 需要频繁创建和销毁的对象
  2. 创建对象耗时或资源消耗大
  3. 工具类对象
  4. 访问数据库或文件的对象
  5. 需要共享访问点或共享数据的场景

注意事项

  1. 多线程环境下的线程安全问题
  2. 序列化和反序列化可能破坏单例
  3. 反射攻击可能破坏单例
  4. 单例模式可能增加代码耦合度
  5. 单例对象生命周期长,可能成为内存泄漏的来源

单例模式是设计模式中最简单的模式之一,但实现一个健壮的单例需要考虑多种因素,特别是在多线程环境下。

全部评论

相关推荐

评论
5
4
分享

创作者周榜

更多
牛客网
牛客企业服务