单例模式

单例模式是设计模式中使用最为普遍的模式之一,它是一种对象创建模式,单例模式可以确保系统中一个类只产生一个实例,而且自行实例化并向整个系统提供这个实例。

好处

  1. 节省系统开销,频繁使用的对象,节省创建花费的时间。
  2. 由于创建次数少,内存使用低,减轻GC压力。

特点

  1. 单例类确保自己只有一个实例。
  2. 单例类必须创建自己的唯一实例。
  3. 单例类必须给所有其他对象提供这一实例。

饿汉

    public class EagerSingleton {
        private static EagerSingleton instance = new EagerSingleton();
        private EagerSingleton(){
        }
        public static EagerSingleton getInstance(){
            return instance;
        }
    }
构造方法私有,instance成员变量和getInstance()是static,jvm加载时,就会被创建。缺点,不支持lazy-loading,会内存常驻。

懒汉

    public class LazySingleton {
    private static LazySingleton instance = null;
    private LazySingleton(){
    }
    public static LazySingleton getInstance(){
        if(instance == null){
            instance = new LazySingleton();
        }
        return instance;
    }
}
非线程安全,多个访问者同时访问,则会产生多个实例。

懒汉加锁

    public class LazySingleton {
    private static LazySingleton instance = null;
    private LazySingleton(){
    }
    public static synchronized LazySingleton getInstance(){
        if(instance == null){
            instance = new LazySingleton();
        }
        return instance;
    }
引入了同步关键字保证线程安全,但降低系统性能。

静态内部类

    public class LazySingleton {
    private LazySingleton(){
    }
    private static class SingletonHolder{
       private static LazySingleton instance = new LazySingleton();
    }

    public static  LazySingleton getInstance(){
        return SingletonHolder.instance;
    }
调用getInstance()时,才会加载SingletonHolder,从而初始化instance。(静态内部类在第一次使用时才会被加载)
原文地址:https://www.cnblogs.com/Ch1nYK/p/8598303.html