什么是单例模式
定义为单例模式的类 在程序中有且只有一个实例
单例模式特点
1. 只有一个实例
2. 构造函数私有化
3. 对外提供获取实例的静态方法
单例的实现
单例有五种实现方式:饿汉、懒汉、双重验证锁、静态内部类、枚举单例
-
饿汉
@Slf4j public class Singleton { /** * 自我实例化 */ private static Singleton singleton = new Singleton(); /** * 构造函数私有化 */ private Singleton() { log.info("这是饿汉式构造函数"); } /** * 对外提供获取实例的静态方法 * @return singleton */ public static Singleton getInstance() { return singleton; } }
-
懒汉
@Slf4j public class Singleton { /** * 自我实例化 */ private static Singleton singleton; /** * 构造函数私有化 */ private Singleton() { log.info("这是懒汉式构造函数"); } /** * 对外提供获取实例的静态方法 * * @return singleton */ public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } }
-
双重验证锁
@Slf4j public class Singleton { /** * 自我实例化 */ private volatile static Singleton singleton; /** * 构造函数私有化 */ private Singleton() { log.info("这是双重验证锁式构造函数"); } /** * 对外提供获取实例的静态方法 * * @return singleton */ public static Singleton getInstance() { // 第一次检查,避免不必要的实例 if (singleton == null) { synchronized (Singleton.class){ // 第一次检查,同步,避免产生多线程的问题 if(singleton == null){ singleton = new Singleton(); } } } return singleton; } }
-
静态内部类
@Slf4j public class Singleton { /** * 构造函数私有化 */ private Singleton() { log.info("这是静态内部类式构造函数"); } private static class SingletonInner{ private static Singleton singleton = new Singleton(); } /** * 对外提供获取实例的静态方法 * * @return singleton */ private static Singleton getInstance() { return SingletonInner.singleton; } }
-
枚举单例
public enum Singleton { INSTANCE; }
-
应用场景:Spring加载/注入类的时候、在使用阿里语音识别时创建的NlsClient对象也是单例的。
文章参考来源:泥瓦匠BYSocket 公众号