JAVA 枚举单例模式

时间:2021-06-05 10:11:58

 1、枚举单例模式的实现  

public enum Singleton {
INSTANCE { @Override
protected void read() {
System.out.println("read");
} @Override
protected void write() {
System.out.println("write");
} };
protected abstract void read();
protected abstract void write();
}

2、枚举单例模式的优点

1、线程安全

  原因:从反编译后的类源码中可以看出也是通过类加载机制保证的反编译后的源码

public abstract class Singleton extends Enum
{ private Singleton(String s, int i)
{
super(s, i);
} protected abstract void read(); protected abstract void write(); public static Singleton[] values()
{
Singleton asingleton[];
int i;
Singleton asingleton1[];
System.arraycopy(asingleton = ENUM$VALUES, , asingleton1 = new Singleton[i = asingleton.length], , i);
return asingleton1;
} public static Singleton valueOf(String s)
{
return (Singleton)Enum.valueOf(singleton/Singleton, s);
} Singleton(String s, int i, Singleton singleton)
{
this(s, i);
} public static final Singleton INSTANCE;
private static final Singleton ENUM$VALUES[]; static
{
INSTANCE = new Singleton("INSTANCE", ) { protected void read()
{
System.out.println("read");
} protected void write()
{
System.out.println("write");
} };
ENUM$VALUES = (new Singleton[] {
INSTANCE
});
}
}

2、不会因为序列化而产生新实例

  不会因为序列化而产生新实例原因:枚举类自己实现了readResolve()方法,所以抗序列化,这个方法是当前类自己实现的(待验证)防止反射攻击

3、防止反射攻击

  由反编译类源码可知单例类的修饰是abstract的,所以没法实例化。