单例模式(Singleton Pattern)是指确保一个类在任何情况下都绝对只有一个实例,并提供一个全局访问点。
隐藏其所有的构造方法。
属于创建型模式。
确保任何情况下都绝对只有一个实例。
第一种:饿汉式单例:在单例类首次加载时就创建实例
/**
* @Package: com.hzg.study.design.pattern.singleton.hungry
* @Description: 饿汉式单例
* @Author: HuangZhiGao
* @CreateDate: 2022-02-18 16:15
*/
public class HungrySingleton {
private static final HungrySingleton INSTANCE = new HungrySingleton();
/**
* 私有化构造器
*/
private HungrySingleton() {
}
/**
* 全局访问点
*/
public static HungrySingleton getInstance() {
return INSTANCE;
}
}
饿汉式单例静态代码块写法:
/**
* @Package: com.hzg.study.design.pattern.singleton.hungry
* @Description: 饿汉式单例(静态代码块初始化)
* @Author: HuangZhiGao
* @CreateDate: 2022-02-18 16:15
*/
public class HungryStaticSingleton {
private static final HungryStaticSingleton INSTANCE;
/**
* 静态代码块
*/
static {
INSTANCE = new HungryStaticSingleton();
}
/**
* 私有化构造器
*/
private HungryStaticSingleton() {
}
/**
* 全局访问点
*/
public static HungryStaticSingleton getInstance() {
return INSTANCE;
}
}
第二种:懒汉式单例:被外部类调用时才创建实例
/**
* @Package: com.hzg.study.design.pattern.singleton.lazy
* @Description: 懒汉式单例
* @Author: HuangZhiGao
* @CreateDate: 2022-02-18 16:24
*/
public class LazySingleton {
private static LazySingleton INSTANCE = null;
/**
* 私有化构造器
*/
private LazySingleton() {
}
/**
* 全局访问点
*/
public static LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
懒汉式单例静态匿名内部类写法(性能最优):
/**
* @Package: com.hzg.study.design.pattern.singleton.lazy
* @Description: 懒汉式单例(匿名静态内部类)(性能最优)
* @Author: HuangZhiGao
* @CreateDate: 2022-02-18 18:00
*/
public class LazyInnerClazzSingleton implements Serializable {
/**
* 私有化构造器
*/
private LazyInnerClazzSingleton() {
}
/**
* 全局访问点
*/
public static final LazyInnerClazzSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazyInnerClazzSingleton INSTANCE = new LazyInnerClazzSingleton();
}
}
第三种:注册式单例:将每一个实例都缓存到统一的容器中,使用唯一标识获取实例
注册式单例枚举写法:
/**
* @Package: com.hzg.study.design.pattern.singleton.registry
* @Description: 注册式单例-枚举单例
* @Author: HuangZhiGao
* @CreateDate: 2022-02-21 10:24
*/
public enum EnumSingleton {
INSTANCE;
/**
* 如果需要让其他对象成为单例,只需要将data改为目标类对象即可
*
* 通过getter和setter操作
*/
private Object data;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public static EnumSingleton getInstance() {
return INSTANCE;
}
}
Spring中常见的注册式单例写法:
/**
* @Package: com.hzg.study.design.pattern.singleton.registry
* @Description: Spring中常见的注册式单例写法
* @Author: HuangZhiGao
* @CreateDate: 2022-02-21 10:54
*/
public class ContainerSingleton {
/**
* spring ioc
*/
private static Map<String, Object> container = new ConcurrentHashMap<>();
private ContainerSingleton() {
}
public static Object getBean(String clazzName) {
// 加synchronized代码块保证线程安全
synchronized (container) {
if (!container.containsKey(clazzName)) {
Object object = null;
try {
object = Class.forName(clazzName).newInstance();
container.put(clazzName, object);
} catch (Exception e) {
e.printStackTrace();
}
return object;
}
return container.get(clazzName);
}
}
}
第四种:ThreadLocal线程单例:保证线程内部的全局唯一,且天生线程安全
/**
* @Package: com.hzg.study.design.pattern.singleton.threadlocal
* @Description: ThreadLocal线程单例(伪安全)
* @Description: 可以使用ThreadLocal动态切换数据源
* @Author: HuangZhiGao
* @CreateDate: 2022-02-21 11:10
*/
public class ThreadLocalSingleton {
public static final ThreadLocal<ThreadLocalSingleton> THREAD_LOCAL = new ThreadLocal<ThreadLocalSingleton>() {
@Override
protected ThreadLocalSingleton initialValue() {
return new ThreadLocalSingleton();
}
};
private ThreadLocalSingleton() {
}
public static ThreadLocalSingleton getInstance() {
return THREAD_LOCAL.get();
}
}
以懒汉式单例LazySingleton为例:
首先写一个线程实现类,如下:
import com.hzg.study.design.pattern.singleton.lazy.LazySingleton;
/**
* @Package: com.hzg.study.design.pattern.singleton.lazy.test
* @Description:
* @Author: HuangZhiGao
* @CreateDate: 2022-02-18 16:32
*/
public class ExecutorThread implements Runnable {
@Override
public void run() {
LazySingleton instance = LazySingleton.getInstance();
System.out.println(Thread.currentThread().getName() + ":" + instance);
}
}
main方法测试:
public class LazySingletonTest {
public static void main(String[] args) {
Thread thread1 = new Thread(new ExecutorThread());
thread1.start();
Thread thread2 = new Thread(new ExecutorThread());
thread2.start();
System.out.println("----------------------------------------");
}
}
测试结果:显然出现了两个不同的实例
解决方法1:加synchronized关键字修饰getInstance方法
public class LazySingleton {
private static LazySingleton INSTANCE = null;
/**
* 私有化构造器
*/
private LazySingleton() {
}
/**
* 全局访问点
*
* synchronized关键字修饰方法
*/
public static synchronized LazySingleton getInstance() {
if (INSTANCE == null) {
INSTANCE = new LazySingleton();
}
return INSTANCE;
}
}
解决方法2:双重检查锁DoubleCheck
/**
* @Package: com.hzg.study.design.pattern.singleton.lazy
* @Description: 懒汉式单例(双重检查锁)
* @Author: HuangZhiGao
* @CreateDate: 2022-02-18 17:08
*/
public class LazyDoubleCheckSingleton {
/**
* volatile关键字修饰,避免指令重排序引发问题
*/
private volatile static LazyDoubleCheckSingleton INSTANCE = null;
/**
* 私有化构造器
*/
private LazyDoubleCheckSingleton() {
}
/**
* 全局访问点
*
* 双重检查锁
*/
public static LazyDoubleCheckSingleton getInstance() {
if (INSTANCE == null) {
synchronized (LazyDoubleCheckSingleton.class) {
if (INSTANCE == null) {
INSTANCE = new LazyDoubleCheckSingleton();
}
}
}
return INSTANCE;
}
}
以懒汉式单例静态匿名内部类写法LazyInnerClazzSingleton为例:
main方法测试:
public class LazyInnerClazzSingletonTest {
public static void main(String[] args) {
try {
Class<LazyInnerClazzSingleton> aClazz = LazyInnerClazzSingleton.class;
Constructor<LazyInnerClazzSingleton> declaredConstructor = aClazz.getDeclaredConstructor(null);
declaredConstructor.setAccessible(true);
LazyInnerClazzSingleton instance1 = declaredConstructor.newInstance();
LazyInnerClazzSingleton instance2 = LazyInnerClazzSingleton.getInstance();
System.out.println(instance1);
System.out.println(instance2);
System.out.println(instance1 == instance2);
} catch (Exception e) {
e.printStackTrace();
}
}
}
解决方法:在构造器中增加如下if判断
public class LazyInnerClazzSingleton implements Serializable {
/**
* 私有化构造器
*/
private LazyInnerClazzSingleton() {
if (null != LazyHolder.INSTANCE) {
throw new RuntimeException("不允许构建多个实例");
}
}
/**
* 全局访问点
*/
public static final LazyInnerClazzSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazyInnerClazzSingleton INSTANCE = new LazyInnerClazzSingleton();
}
}
以懒汉式单例静态匿名内部类写法LazyInnerClazzSingleton为例:注意必须先实现序列化接口Serializable
main方法测试:
public static void main(String[] args) {
LazyInnerClazzSingleton instance1 = LazyInnerClazzSingleton.getInstance();
LazyInnerClazzSingleton instance2 = null;
try (
FileOutputStream fileOutputStream = new FileOutputStream("LazyInnerClazzSingleton.obj");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
FileInputStream fileInputStream = new FileInputStream("LazyInnerClazzSingleton.obj");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
) {
// 序列化
objectOutputStream.writeObject(instance1);
objectOutputStream.flush();
// 反序列化
instance2 = (LazyInnerClazzSingleton) objectInputStream.readObject();
System.out.println(instance1);
System.out.println(instance2);
System.out.println(instance1 == instance2);
} catch (Exception e) {
e.printStackTrace();
}
}
测试结果:构建了两个不同的实例
解决方法:新增readResolve方法
public class LazyInnerClazzSingleton implements Serializable {
/**
* 私有化构造器
*/
private LazyInnerClazzSingleton() {
if (null != LazyHolder.INSTANCE) {
throw new RuntimeException("不允许构建多个实例");
}
}
/**
* 全局访问点
*/
public static final LazyInnerClazzSingleton getInstance() {
return LazyHolder.INSTANCE;
}
private static class LazyHolder {
private static final LazyInnerClazzSingleton INSTANCE = new LazyInnerClazzSingleton();
}
/**
* 重写readResolve方法,实际还是创建了两次,只不过是覆盖了反序列化出来的对象,之前反序列化出来的对象会被GC回收
* 发生在JVM层面,相对来说比较安全
*/
private Object readResolve() {
return LazyHolder.INSTANCE;
}
}
优点:
在内存中只有一个实例,减少了内存开销。
可以避免对资源的多重占用。
设置全局访问点,严格控制访问。
缺点:
没有接口,扩展困难。
如果要扩展单例对象,只有修改代码,没有其他途径。
不符合开闭原则
1、私有化构造器
2、保证线程安全
3、延迟加载
4、防止序列化和反序列化破坏单例
5、防御反射攻击单例