首页 > 代码库 > 防止单例在反序列化后成多例

防止单例在反序列化后成多例

无意中看到这个方法,突然对JAVA很失望,没有任何接口,就这么空降般的一个私有方法,像类似的方法还有多少?n久以后我可能忘记,就在这做个备忘吧!


package com.godway.test;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * 防止单例在反序列化后成多例
 * readResolve方法测试
 * @author godway
 */
public class TestSingleton implements Serializable {
	private static final long serialVersionUID = 810160916916358307L;
	
	// 单例
	public static final TestSingleton instance = new TestSingleton();
	public static TestSingleton getInstance(){
		return instance;
	}
	private TestSingleton(){
	}
	
	/**
	 * 防止单例对象在序列化后生成“多例”
	 * 
	 * @return
	 * @throws ObjectStreamException
	 */
	private Object readResolve() throws ObjectStreamException {
		return instance;
	}
	
	/**
	 * 序列化克隆
	 * @return
	 * @throws Exception
	 */
	public TestSingleton deepCopy() throws Exception{
		ByteArrayOutputStream os = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(os);
		oos.writeObject(TestSingleton.getInstance());
		
		InputStream is = new ByteArrayInputStream(os.toByteArray());
		ObjectInputStream ois = new ObjectInputStream(is);
		TestSingleton test = (TestSingleton) ois.readObject();
		return test;
	}

	public static void main(String args[]) {
		/**
		 * 这样打印出的TestSingleton对象地址一致,
		 * 说明依然是单例对象
		 * 把readResolve方法注释掉再来一遍看看呢?
		 */
		System.out.println(TestSingleton.getInstance());
		try {
			System.out.println(TestSingleton.getInstance().deepCopy());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}



防止单例在反序列化后成多例