Java和ABAP单例(singleton)设计模式的攻与防

简介: Java和ABAP单例(singleton)设计模式的攻与防

Recently I meet with an issue using Spring which finally turns out that my bean is initialized multiple times although it is expected to be a singleton. As a result I look into the possible scenario that might bypass the expected singleton behavior.


This blog introduces two possible scenarios which will cause your singleton design fail to work as expected.


This is my singleton class in ABAP:


image.png

image.pngimage.png

Via comparison in debugger we can know that the instance got from deserialization is a different instance from the original one returned by GET_INSTANCE.


[图片]


In Java it is even not necessary to use this approach to bypass the singleton. It is enough to just use reflection.

This is my singleton class:

image.png

And I can still create new instance via reflection:image.png

finally I get false in console.

In Java this bypass action could be defended by using a boolean variable to detect whether the constructor has already been executed or not. If the constructor is called with value equals to true, it means the constructor has been executed repeatedly, then we raise exception.

The source code of improved singleton is listed below:

image.png

The better solution is to leverage Java Enumeration:

image.png

相关文章
|
1月前
|
设计模式 Java
26、Java 简单实现单例设计模式(饿汉式和懒汉式)
26、Java 简单实现单例设计模式(饿汉式和懒汉式)
28 2
|
21天前
|
设计模式 安全 Java
在Java中即指单例设计模式
在Java中即指单例设计模式
15 0
|
8月前
|
设计模式 Java
Java反射(Class、反射实例化、反射与单例、获取类结构)附带相关面试题
1.了解反射,2.Class类的三种实例化方法,3.反射机制与对象实例化,4.反射与单例设计模式,5.通过反射获取类结构的信息
196 0
|
8月前
|
设计模式 Java 安全
Java中包的作用以及使用、访问权限、单例/多例设计模式、枚举和异常(附带相关面试题)
本章节讲述以下方面知识点 1.包的作用以及使用 2.单例/多例化设计模式 3.枚举 4.访问权限2.异常
54 0
Java中包的作用以及使用、访问权限、单例/多例设计模式、枚举和异常(附带相关面试题)
|
4月前
|
SQL 安全 Java
java单例——Java 内存模型之从 JMM 角度分析 DCL
java单例——Java 内存模型之从 JMM 角度分析 DCL
36 0
|
4月前
|
设计模式 安全 Java
【单例模式】饿汉式,懒汉式?JAVA如何实现单例?线程安全吗?
【单例模式】饿汉式,懒汉式?JAVA如何实现单例?线程安全吗?
28 0
|
4月前
|
Java
Java单例---双重锁校验详解
Java单例---双重锁校验详解
39 0
|
4月前
|
Java
Java单例---反射攻击破坏单例和解决方法
Java单例---反射攻击破坏单例和解决方法
30 0
|
4月前
|
安全 Java
Java单例---静态内部类
Java单例---静态内部类
28 0
|
4月前
|
安全 Java
Java单例---序列化破坏单例模式原理解析(二)
Java单例---序列化破坏单例模式原理解析
24 0