简介:单例模式是设计模式中使用比较广泛的设计模式,也是很是简单的一种设计模式。单例模式是指确保系统中只有一个实例。最多见的单例模式分为懒汉模式和饿汉模式。java
1. 单例模式的好处:设计模式
1)对于频繁使用的对象,能够省去建立对象的开销;多线程
2)因为new操做的次数减小,于是对系统内存的使用频率也会下降,从而减小系统GC的时间。性能
2. 单例模式造成的条件优化
1)必需要有一个私有构造器spa
2)单例对象变量须要是私有的静态static线程
3. 饿汉模式( 这个汉子太饿了,一上来就直接new 对象实例)设计
实现代码:code
SingletonDemoHungry.java对象
/** * <p>Description: 单例模式 * 饿汉模式 * </p> * @author Huang Xiaocong * @data 2019年10月27日 */ public class SingletonDemoHungry { private SingletonDemoHungry() { //私有构造器 System.out.println("建立单例模式"); //实际开发中,建立单例模式的时候可能比较慢 } private static SingletonDemoHungry instance = new SingletonDemoHungry(); public static SingletonDemoHungry getInstance() { return instance; } }
优势:这种单例模式的实现方式简单可靠。
缺点:没法对对象实例(instance)作延迟加载。假如在单例的建立过程很慢,而因为instance成员变量是static定义的,因此在加载单例类的过程当中也会一块儿加载。若单例类中还存在其余static方法或者变量,也会一块儿加载。而且在其余地方使用该单例类时也会被加载屡次。
如SingletonDemoHungry.java单例类中还存在其余静态方法:
public static void printInfo() { System.out.println("printInfo in SingletonDemoHungry!!"); }
在其余地方调用SingletonDemoHungry.printInfo(); 时, 程序将打印以下信息。程序并无使用单例类,但instance实例仍是被建立出来了。
建立单例模式
printInfo in SingletonDemoHungry!!
为了解决上述这个问题,可使用饿汉模式。
4.懒汉模式(这个汉子太懒了,直到要使用的时候才new 对象)
SingletonDemoLazy.java
/** * <p>Description: 懒汉模式</p> * @author Huang Xiaocong * @data 2019年10月27日 */ public class SingletonDemoLazy { private static SingletonDemoLazy instance = null; private SingletonDemoLazy() { System.out.println("建立单例模式"); //实际开发中,建立单例模式的时候可能比较慢 } public static synchronized SingletonDemoLazy getInstance() { if(instance == null) { instance = new SingletonDemoLazy(); } return instance; } }
该懒汉模式与饿汉模式相比,引入了延迟加载机制。但其中的getInstance()方法必须是同步的,不然在多线程环境下,当线程1在新建单例时,建立完正打算赋值时,线程2可能判断instance为null,同时进行建立对象,而致使多个实例被建立。虽然实现了延迟加载的功能,可是同时又引入了新的问题,使用synchronized关键字,在多线程环境中,它的时耗远远大于饿汉模式。
为了使用延迟加载反而下降了系统性能,得不偿失,可对其进行改进优化:
/** * <p>Description: 改进的懒汉模式</p> * @author Huang Xiaocong * @data 2019年10月27日 */ public class SingletonDemoNewLazy { private SingletonDemoNewLazy() { System.out.println("SingletonDemoNewLazy.SingletonDemoNewLazy()"); } //内部类SingletonHolder private static class SingletonHolder { private static SingletonDemoNewLazy instance = new SingletonDemoNewLazy(); } public static SingletonDemoNewLazy getInstance() { return SingletonHolder.instance; } }
改进后的单例模式使用内部类维护单例类的实例,当SingletonDemoNewLazy被加载时,其内部类并不会被初始化。而只有当调用getInstance()方法时才会调用加载SingletonHolder。即最后的SingletonDemoNewLazy.java既实现了延迟加载,也没必要使用同步机制。