当前位置: 首页 > news >正文

设计模式之破环单例模式和阻止破坏

目录

  • 1. 序列化和反序列化
  • 2. 反射

这里单例模式就不多说了
23种设计模式之单例模式

1. 序列化和反序列化

这里用饿汉式来做例子
LazySingleton

import java.io.Serializable;public class LazySingleton implements Serializable {private static LazySingleton lazySingleton = null;private LazySingleton() {}public static synchronized LazySingleton getInstance() {if (lazySingleton == null) {lazySingleton = new LazySingleton();}return lazySingleton;}
}

TestSerializer

import java.io.*;public class TestSerializer {public static void main(String[] args) throws IOException, ClassNotFoundException {// 懒汉式LazySingleton instance = LazySingleton.getInstance();// 通过序列化和反序列化的方式,创建对象ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("singleton"));oos.writeObject(instance);ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("singleton")));LazySingleton objInstance = (LazySingleton)ois.readObject();System.out.println(instance);System.out.println(objInstance);}
}

输出结果:

yxz.singleton.LazySingleton@3764951d
yxz.singleton.LazySingleton@312b1dae

可以看到这俩对象不一样。
但是使用枚举输出结果是一样的。

如果不让其破坏呢???

我们在单例中添加一个方法。

import java.io.Serializable;public class LazySingleton implements Serializable {private static LazySingleton lazySingleton = null;private LazySingleton() {}public static synchronized LazySingleton getInstance() {if (lazySingleton == null) {lazySingleton = new LazySingleton();}return lazySingleton;}private Object readResolve() {return lazySingleton;}
}

输出结果:

yxz.singleton.LazySingleton@3764951d
yxz.singleton.LazySingleton@3764951d

这样输出结果是一样的了。因为反序列化创建对象时,是通过反射创建的,反射会调用我们自己的readResolve方法,如果重写,会调用这个,否则会破坏单例模式。

2. 反射

通过字节码对象创建构造器对象,通过构造器对象,初始化单例对象,由于单例对象的构造方法是私有化的,调用构造器中的方法,赋予权限,创建单例对象。

TestReflect

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;public class TestReflect {public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {Class clz = LazySingleton.class;// 通过字节码对象创建构造器对象Constructor constructor = clz.getDeclaredConstructor();// 赋予权限constructor.setAccessible(true);// 初始化单例对象LazySingleton clzInstance = (LazySingleton)constructor.newInstance();System.out.println(clzInstance);LazySingleton instance = LazySingleton.getInstance();System.out.println(instance);}
}

输出结果:

yxz.singleton.LazySingleton@1b6d3586
yxz.singleton.LazySingleton@4554617c

坏了,又是一样的,这可怎么办!!!
我们如何阻止呢?
我们对代码的构造模式进行修改

import java.io.Serializable;public class LazySingleton implements Serializable {private static LazySingleton lazySingleton = null;private LazySingleton() {if(lazySingleton != null){throw new RuntimeException("不允许创建多个实例");}}public static synchronized LazySingleton getInstance() {if (lazySingleton == null) {lazySingleton = new LazySingleton();}return lazySingleton;}private Object readResolve() {return lazySingleton;}
}

这样我们再运行,输出结果是:

yxz.singleton.LazySingleton@1b6d3586
yxz.singleton.LazySingleton@4554617c

恭喜你,仍然能出现两个!!!但是,我们先创建一个对象,再使用反射呢?

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;public class TestReflect {public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {LazySingleton instance = LazySingleton.getInstance();System.out.println(instance);Class clz = LazySingleton.class;Constructor constructor = clz.getDeclaredConstructor();constructor.setAccessible(true);LazySingleton clzInstance = (LazySingleton)constructor.newInstance();System.out.println(clzInstance);}
}

运行结果:

yxz.singleton.LazySingleton@1b6d3586
Exception in thread "main" java.lang.reflect.InvocationTargetExceptionat sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)at java.lang.reflect.Constructor.newInstance(Constructor.java:423)at yxz.singleton.broker.TestReflect.main(TestReflect.java:16)
Caused by: java.lang.RuntimeException: 不允许创建多个实例at yxz.singleton.LazySingleton.<init>(LazySingleton.java:10)... 5 more

这才没有创建多个。

当然,我建议是使用枚举来组织它,不过,我在使用的时候,还是没怎怎么故意使用反射或者序列化这些来破坏单例模式。

http://www.lryc.cn/news/492901.html

相关文章:

  • 11.19c++面向对象+单例模式
  • 一文了解TensorFlow是什么
  • 如何做好一份技术文档?
  • Linux和Ubuntu的关系
  • 软件工程之静态建模
  • PICO VR串流调试Unity程序
  • 自媒体图文视频自动生成软件|03| 页面和结构介绍
  • 深入浅出摸透AIGC文生图产品SD(Stable Diffusion)
  • 解析生成对抗网络(GAN):原理与应用
  • CodeIgniter URL结构
  • 从 App Search 到 Elasticsearch — 挖掘搜索的未来
  • 鸿蒙本地模拟器 模拟TCP服务端的过程
  • Qt/C++基于重力模拟的像素点水平堆叠效果
  • Zookeeper学习心得
  • 嵌入式开发工程师面试题 - 2024/11/24
  • Python中打印当前目录文件树的脚本
  • 全景图像(Panorama Image)向透视图像(Perspective Image)的跨视图转化(Cross-view)
  • Redis 中的 hcan 命令耗内存,有什么优化的方式吗 ?
  • 豆包MarsCode算法题:三数之和问题
  • 【Android】AnimationDrawable帧动画的实现
  • 【消息序列】详解(7):剖析回环模式--设备测试的核心利器
  • 解决Ubuntu 22.04系统中网络Ping问题的方法
  • 【大数据学习 | Spark-SQL】Spark-SQL编程
  • 15分钟做完一个小程序,腾讯这个工具有点东西
  • manim动画编程(安装+入门)
  • STL算法之数值算法<stl_numeric.h>
  • Oracle如何记录登录用户IP
  • Python图像处理:打造平滑液化效果动画
  • 构建Ceph分布式文件共享系统:手动部署指南
  • 数据结构——用数组实现栈和队列