单例,就是整个程序有且仅有一个实例。该类负责创建自己的对象,同时确保只有一个对象被创建。它的出现是为了节省资源。在Spring中,每个Bean默认就是单例的。在Java,一般常用在工具类的实现或创建对象需要消耗资源。
单例模式分为懒汉式和饿汉式:
饿汉模式
线程安全,比较常用,效率高,但容易产生垃圾,因为一开始就初始化,不能延时加载
1 package top.bigking.singleton; 2 3 /** 4 * @Author ABKing 5 * @Date 2020/1/31 下午5:50 6 * 单例模式之 饿汉式 7 **/ 8 public class SingletonDemo1 { 9 private static SingletonDemo1 instance = new SingletonDemo1();//类初始化时,立即加载 10 private SingletonDemo1(){}; 11 public static SingletonDemo1 getInstance(){ 12 return instance; 13 } 14 }
懒汉模式
线程不安全,延迟初始化,效率低偏低,严格意义上不是不是单例模式,可以延时加载
1 package top.bigking.singleton; 2 3 /** 4 * @Author ABKing 5 * @Date 2020/1/31 下午5:50 6 * 单例模式之 懒汉式 7 **/ 8 public class SingletonDemo2 { 9 private static SingletonDemo2 instance; 10 private SingletonDemo2(){}; 11 public static synchronized SingletonDemo2 getInstance(){ 12 if(instance == null){ 13 instance = new SingletonDemo2(); 14 } 15 return instance; 16 } 17 }
双重检测锁
1 package top.bigking.singleton; 2 3 /** 4 * @Author ABKing 5 * @Date 2020/2/3 下午6:48 6 * 单例模式之 双重检测锁 7 **/ 8 public class SingletonDemo3 { 9 private static SingletonDemo3 instance; 10 private SingletonDemo3(){}; 11 public static SingletonDemo3 getInstance(){ 12 if(instance == null){ 13 SingletonDemo3 sc; 14 synchronized (SingletonDemo3.class){ 15 sc = instance; 16 } 17 if(sc == null){ 18 synchronized (SingletonDemo3.class){ 19 if(sc == null){ 20 sc = new SingletonDemo3(); 21 } 22 } 23 instance = sc; 24 } 25 } 26 return instance; 27 } 28 }
静态内部类
1 package top.bigking.singleton; 2 3 /** 4 * @Author ABKing 5 * @Date 2020/2/3 下午8:32 6 * 单例模式 之 静态内部类 7 **/ 8 public class SingletonDemo4 { 9 //懒加载,而且类的加载是天然的线程安全的,当调用getInstance()方法时,才会加载 静态内部类 10 private static class SingletonClassInstance { 11 private static final SingletonDemo4 instance = new SingletonDemo4(); 12 } 13 //直接调用,不需要synchronized同步等待,高效并发 14 public static SingletonDemo4 getInstance(){ 15 return SingletonClassInstance.instance; 16 } 17 private SingletonDemo4(){}; 18 19 }
原文:https://www.cnblogs.com/ABKing/p/12227234.html