单例模式的5种实现方式


public class Test {

    // 饿汉式,线程安全,但提前加载,浪费内存
    private static Test instance = new Test();

    private static Test getInstance() {
        return instance;
    }

    private static Test instance2;

    // 懒汉式,线程不安全,但使用时加载省内存
    private static Test getInstance2(){
        if (instance2 == null) {
            instance2 = new Test();
        }
        return instance2;
    }

    // 懒汉式DLC,double check lock 双重检测锁(DLC),线程安全
    // 注意:instance3 要用volatile修饰才能保证线程安全
    private static volatile Test instance3;

    private static Test getInstance3(){
        if (instance3 == null){
            synchronized (Test.class) {
                if (instance3 == null){
                    instance3 = new Test();
                }
            }
        }
        return instance3;
    }

    //内部类方式,推荐,线程安全,调用getInstance4时才加载省内存
    static class TestInner {

        private static final Test INSTANCE4 = new Test();

        public static Test getInstance4() {
            return TestInner.INSTANCE4;
        }
    }

    // 枚举式,极力推荐,线程安全且只会在使用时装载一次,且序列化、反序列化、反射或克隆都不会创建对象
    enum TestEnum{
        INSTANCE;

        final Test instance5;

        TestEnum(){
            this.instance5 = new Test();
        }

        public Test getInstance5(){
            return instance5;
        }
    }

    public void sayHi(){
        System.out.println("Hi");
    }


    public static void main(String[] args) {
        Test instance = Test.getInstance();
        instance.sayHi();

        Test instance2 = Test.getInstance2();
        instance2.sayHi();

        Test instance3 = Test.getInstance3();
        instance3.sayHi();

        Test instance4 = Test.TestInner.getInstance4();
        instance4.sayHi();

        Test instance5 = TestEnum.INSTANCE.getInstance5();
        instance5.sayHi();
    }
}

posted @ 2022-11-10 10:34  lixuelong  阅读(26)  评论(0编辑  收藏  举报