饿汉式单例模式
反射,unsafe,反序列化可破坏单例
package singleton;
import java.io.Serializable;
/**
*
* 饿汉单例
* @date 2022/10/30/030 23:33
*/
public class HungrySingleton implements Serializable {
/**
* 私有的构造器
*/
private HungrySingleton() {}
/**
* static 和final 修饰的成员变量
*/
private static final HungrySingleton INSTANCE = new HungrySingleton();
public static HungrySingleton getInstance() {
return INSTANCE;
}
}
枚举饿汉单例
只有unsafe可以破坏单例
package singleton;
public enum EnumHungrySingleton {
INSTANCE;
EnumHungrySingleton() {
}
public static EnumHungrySingleton getInstance() {
return INSTANCE;
}
}
测试方法
package singleton;
import java.lang.reflect.Constructor;
public class TestHungrySingleton {
public static void main(String[] args) throws Exception {
HungrySingleton instance1 = HungrySingleton.getInstance();
HungrySingleton instance2 = HungrySingleton.getInstance();
System.out.println("位置一:"+(instance1 == instance2));
HungrySingleton reflectionInstance = reflection(HungrySingleton.class);
System.out.println("位置二:"+(instance1 == reflectionInstance));
/**
* Enum单例测试
*/
EnumHungrySingleton enumHungrySingleton1 = EnumHungrySingleton.getInstance();
EnumHungrySingleton enumHungrySingleton2 = EnumHungrySingleton.getInstance();
System.out.println("位置三:"+(enumHungrySingleton1==enumHungrySingleton2));
}
private static HungrySingleton reflection(Class<?> clazz) throws Exception {
Constructor<?> constructor = clazz.getDeclaredConstructor();
constructor.setAccessible(true);
return (HungrySingleton) constructor.newInstance();
}
}
输出:
位置一:true
位置二:false
位置三:true