枚举类实现单例,添加枚举类内部方法,反编译文件展示
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
package top.fjy8018.designpattern.pattern.creational.singleton;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
/**
|
||||
* 枚举单例模式(effective Java推荐)
|
||||
* 枚举类天生可序列化,有效防止序列化攻击
|
||||
@@ -13,11 +15,21 @@ package top.fjy8018.designpattern.pattern.creational.singleton;
|
||||
* @author F嘉阳
|
||||
* @date 2018-09-24 20:30
|
||||
*/
|
||||
@Slf4j
|
||||
public enum EnumInstance {
|
||||
/**
|
||||
* 单例枚举
|
||||
*/
|
||||
INSTANCE;
|
||||
INSTANCE {
|
||||
@Override
|
||||
protected void logTest() {
|
||||
log.info(EnumInstance.class.getSimpleName() + "打印输出");
|
||||
}
|
||||
};
|
||||
|
||||
public static EnumInstance getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
|
||||
/**
|
||||
* 目标实例化对象
|
||||
@@ -32,7 +44,6 @@ public enum EnumInstance {
|
||||
this.data = data;
|
||||
}
|
||||
|
||||
public Object getInstance() {
|
||||
return INSTANCE;
|
||||
}
|
||||
// 提供外部访问方法入口
|
||||
protected abstract void logTest();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
package top.fjy8018.designpattern.pattern.creational.singleton;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class EnumInstanceTest {
|
||||
|
||||
@Test
|
||||
void logTest() {
|
||||
EnumInstance instance = EnumInstance.getInstance();
|
||||
instance.logTest();
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,6 @@ import java.lang.reflect.Constructor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 单例模式反射攻击
|
||||
*/
|
||||
@@ -37,7 +35,7 @@ class SingletonReflectAttack {
|
||||
// 通过反射获取实例
|
||||
EnumInstance reflectInstance = (EnumInstance) constructor.newInstance("fjy", 123);
|
||||
// 通过正常方式获取
|
||||
EnumInstance instance = EnumInstance.INSTANCE;
|
||||
EnumInstance instance = EnumInstance.getInstance();
|
||||
|
||||
// 判断是否同一个对象
|
||||
log.info("反射方式:" + reflectInstance.getData());
|
||||
|
||||
@@ -41,7 +41,7 @@ class SingletonSerializableAttackTest {
|
||||
@Test
|
||||
void EnumInstanceGetInstance() throws Exception {
|
||||
|
||||
EnumInstance singleton = EnumInstance.INSTANCE;
|
||||
EnumInstance singleton = EnumInstance.getInstance();
|
||||
singleton.setData(new Object());
|
||||
|
||||
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(FILE_NAME));
|
||||
|
||||
Reference in New Issue
Block a user