单例模式(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));
    }
}
相关推荐
重生之我在字节当程序员11 小时前
如何实现单例模式?
单例模式
夕泠爱吃糖11 小时前
如何实现单例模式?
单例模式
m0_6075487611 小时前
什么是单例模式
开发语言·javascript·单例模式
Am心若依旧40911 小时前
[c++进阶(三)]单例模式及特殊类的设计
java·c++·单例模式
因特麦克斯11 小时前
如何实现对象的克隆?如何实现单例模式?
c++·单例模式
狐拾叁3 天前
设计模式-创建者模式-单例模式(java版)
java·单例模式·设计模式
benben0443 天前
Unity3D仿星露谷物语开发5之角色单例模式
unity·单例模式·游戏引擎
Mr.134 天前
如何实现对象的克隆?如何实现单例模式?
c++·单例模式
missu2174 天前
C++中如何实现单例模式?
开发语言·c++·单例模式
行走的生活4 天前
为什么要用单例模式?
单例模式