enum实现单例模式与一般单例模式的比较

主要在序列化反序列化上的区别。

一个例子可以讲清楚


package com.test;


import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


public class EnumTest {
public static void main(String[] args) throws Exception {
Singleton s = Singleton.getInstance();
Singleton2 es = Singleton2.INSTANCE;


FileOutputStream fos = new FileOutputStream("out.data");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(s);
oos.writeObject(es);
fos.close();
oos.close();


FileInputStream fis = new FileInputStream("out.data");
ObjectInputStream ois = new ObjectInputStream(fis);
Object o = ois.readObject();
Object o2 = ois.readObject();
fis.close();
ois.close();


Singleton s1 = (Singleton) o;
Singleton2 es1 = (Singleton2) o2;


System.out.println(s == s1);
System.out.println(es == es1);
System.out.println("----------------------");


}
}


class Singleton implements Serializable {
private static final long serialVersionUID = 1L;


private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}


private Singleton() {
}


public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}


enum Singleton2 implements Serializable {


INSTANCE;
}


你可能感兴趣的:(JavaSE)