简介:单例模式是设计模式中使用比较普遍的设计模式,也是非常简单的一种设计模式。单例模式是指确保系统中只有一个实例。最常见的单例模式分为懒汉模式和饿汉模式。
1. 单例模式的好处:
1)对于频繁使用的对象,可以省去创建对象的开销;
2)由于new操作的次数减少,因而对系统内存的使用频率也会降低,从而减少系统GC的时间。
2. 单例模式形成的条件
1)必须要有一个私有构造器
2)单例对象变量需要是私有的静态static
3. 饿汉模式( 这个汉子太饿了,一上来就直接new 对象实例)
实现代码:
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既实现了延迟加载,也不必使用同步机制。