单例模式总结

2020-08-18  本文已影响0人  谢伟浩

参考:https://www.cnblogs.com/jing-an-feng-shao/p/7495048.html

1 单例模式

《Head First 设计模式》:确保一个类只有一个实例,并提供一个全局访问点
其目的在于减少系统对于同一个对象的创建和销毁,从而减少内存的开销。

2 实现方法

2.1 饿汉模式

思想:
  饿汉模式是最常提及的2种单例模式之一,其核心思想,是类持有一个自身的 instance 属性,并且在申明的同时立即初始化。
  同时,类将自身的构造器权限设为 private,防止外部代码创建对象,对外只提供一个静态的 getInstance() 方法,作为获取单例的唯一入口。

public class EagerSingleton {
    
    private final static EagerSingleton instance = new EagerSingleton();
    
    private EagerSingleton () {
        if(instance != null) {  //使构造器只能被调用一次
            throw new IllegalStateException();
        }
    }
    
    public static EagerSingleton getInstance() {
        return instance;
    }
    
}

三个要点:

测试Demo如下:

public class DemoSingleton {
    
    public static void main(String[] args) {
        EagerSingleton e1 = EagerSingleton.getInstance();
        EagerSingleton e2 = EagerSingleton.getInstance();
        System.out.println(e1 == e2); //结果为true
        
        //使用方式调用构造器新建实例
        try {
            Class<?> eagerSingletonClass = Class.forName("EagerSingleton");
            Constructor<?> declaredConstructorBook = eagerSingletonClass.getDeclaredConstructor();
            declaredConstructorBook.setAccessible(true);
            Object e = declaredConstructorBook.newInstance(); //调用构造器返回IllegalStateException异常
            System.out.println(e == e1); //如果构造器没限定代码会打印出false,说明没有限定代码反射可以打破单例
        } catch (ClassNotFoundException | InstantiationException 
                | IllegalAccessException | NoSuchMethodException 
                | SecurityException | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
    }

}

2.2 懒汉模式

思想:
  相比于饿汉模式,懒汉模式实际中的应用更多,因为在系统中,“被用到时再初始化”是更佳的解决方案。
  设计思想与饿汉模式类似,同样是持有一个自身的引用,只是将 new 的动作延迟到 getinstance() 方法中执行。

class LazySingleton {
    private static LazySingleton instance;
    
    private LazySingleton() {
        if(instance != null) {
            throw new IllegalStateException();
        }
    }
    
    public static synchronized LazySingleton getInstance() {
        if(instance == null) {
            instance = new LazySingleton();
        }
        return instance;
    }
}

2.3 静态内部类模式

class StaticInnerSingleton {
    private static class Holder {
        private static StaticInnerSingleton instatnce = new StaticInnerSingleton();
    }
    
    private StaticInnerSingleton () {
        if(Holder.instatnce != null) {
            throw new IllegalStateException();
        }
    }
    
    public static StaticInnerSingleton getInstance() {
        return Holder.instatnce;
    }
}

3 总结

实现方法 优势 劣势 阻止反射入侵 阻止多线程入侵
饿汉模式 额外增加内存的消耗
懒汉模式 延迟加载 不能完全屏蔽反射入侵 ×
静态内部类模式 延迟加载 只能通过 JVM 去控制器生命周期,不能手动 destroy
上一篇 下一篇

猜你喜欢

热点阅读