单例模式(Java实现)

1. 懒汉式线程不安全

java 复制代码
public class LazyUnsafeSingleton {
    private static LazyUnsafeSingleton singleton;

    private LazyUnsafeSingleton(){}

    public static LazyUnsafeSingleton getInstance() {
        if (singleton == null) singleton = new LazyUnsafeSingleton();
        return singleton;
    }
}

2. 饿汉式(线程安全)

java 复制代码
public class HungrySingleton {
    private static HungrySingleton singleton = new HungrySingleton();

    private HungrySingleton(){}

    public static HungrySingleton getInstance() {
        return singleton;
    }
}

3. 懒汉式线程安全

volatile
synchronized

java 复制代码
public class LazySafeSingleton {
    private static volatile LazySafeSingleton singleton;

    private LazySafeSingleton(){}

    public static synchronized LazySafeSingleton getInstance() {
        if (singleton == null) singleton = new LazySafeSingleton();
        return singleton;
    }
}

4. 双重检查锁

java 复制代码
public class DoubleCheckedLockSingleton {
    private static volatile DoubleCheckedLockSingleton singleton;

    private DoubleCheckedLockSingleton(){}

    public static DoubleCheckedLockSingleton getInstance() {
        if (singleton == null) {
            synchronized (DoubleCheckedLockSingleton.class) {
                if (singleton == null) {
                    singleton = new DoubleCheckedLockSingleton();
                }
            }
        }
        return singleton;
    }
}

5. 静态内部类

java 复制代码
public class StaticInnerClassSingleton {
    private static StaticInnerClassSingleton singleton;

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

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

6. 枚举类型

java 复制代码
public enum EnumSingleton {
    SINGLETON;

    public String doSomeThing() {
        return "hello world";
    }
}

测试类

java 复制代码
public class SingletonTest {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, InterruptedException {
        // 1. 懒汉式线程非安全
        LazyUnsafeSingleton lazyUnsafeSingleton = LazyUnsafeSingleton.getInstance();

        // 2. 饿汉式
        HungrySingleton hungrySingleton = HungrySingleton.getInstance();

        // 3. 懒汉式线程安全
        LazySafeSingleton lazySafeSingleton = LazySafeSingleton.getInstance();

        // 4. 双重检查锁
        DoubleCheckedLockSingleton doubleCheckedLockSingleton = DoubleCheckedLockSingleton.getInstance();

        // 5. 静态内部类
        StaticInnerClassSingleton staticInnerClassSingleton = StaticInnerClassSingleton.getInstance();

        // 6. 枚举类型
        EnumSingleton enumSingleton = EnumSingleton.SINGLETON;
        enumSingleton.doSomeThing();

        // 反射无法破坏枚举类型的单例模式
        Class<EnumSingleton> enumSingletonClass = EnumSingleton.class;
//        Constructor<EnumSingleton> declaredConstructor = enumSingletonClass.getDeclaredConstructor();
        Constructor<?> declaredConstructor = enumSingletonClass.getDeclaredConstructors()[0];
        declaredConstructor.setAccessible(true);
        Object enumSingleton1 = declaredConstructor.newInstance(); // java.lang.IllegalArgumentException


        // 7. 反射破坏非枚举类型的单例模式
        // (1)获取 Singleton 类的 Class 对象
        Class<LazyUnsafeSingleton> lazyUnsafeSingletonClass = LazyUnsafeSingleton.class;

        // (2)获取 Singleton 类的私有构造函数
        Constructor<LazyUnsafeSingleton> constructor = lazyUnsafeSingletonClass.getDeclaredConstructor();

        // (3)设置私有构造函数的可访问性
        constructor.setAccessible(true);

        // (4)使用私有构造函数创建新的实例
        LazyUnsafeSingleton lazyUnsafeSingletonFromReflect = constructor.newInstance();

        // 打印新创建的实例和原始实例是否相等
        System.out.println("Original Instance: " + LazyUnsafeSingleton.getInstance());
        System.out.println("New Instance: " + lazyUnsafeSingletonFromReflect);
        System.out.println("Are instances equal? " + (LazyUnsafeSingleton.getInstance() == lazyUnsafeSingletonFromReflect));
    }
}
相关推荐
C++忠实粉丝2 天前
Linux系统基础-多线程超详细讲解(5)_单例模式与线程池
linux·运维·服务器·c++·算法·单例模式·职场和发展
FANGhelloworld3 天前
C++面向对象设计模式——单例模式
c++·单例模式·设计模式
土了个豆子的3 天前
单例模式的概念和用处
单例模式
飞升不如收破烂~3 天前
在Spring框架中,容器管理的bean可以有不同的作用域(scope),其中最常用的两种是单例(singleton)和原型(prototype)。
spring·单例模式·原型模式
晨曦丿3 天前
设计模式之——单例模式
c++·单例模式·设计模式
徐子童4 天前
多线程案例---单例模式
java·单例模式·设计模式
楠枬4 天前
Java 反射
java·开发语言·反射
Good_tea_h5 天前
线程安全的单例模式(Singleton)。
单例模式
Tang Paofan5 天前
C++单例模式
java·c++·单例模式
nice666606 天前
DAO模式及单例模式
java·数据库·sql·mysql·单例模式·idea