Java 单例模式:使用私有构造函数强化singleton属性

今天看了《Effective Java》,看到第二条,然后就写了些代码来测试了下加与不加readResolve()方法  是否会产生不同的实例。

/**
 * @(#)singleton.java
 *
 *
 * @author 
 * @version 1.00 2019/9/22
 */
 import java.io.*;


class Elvis implements Serializable{

    private static final Elvis instance = new Elvis();
    
    private int data;
    
    public static Elvis getInstance(){
    	return instance;
    }
    
    public void setData(int d)
    {
    	this.data = d;
    }
    
    public int getData(){
    	return this.data;
    }
    
    private Object readResolve() throws ObjectStreamException{
    	return instance;
    }
    
}

public class  singleton {
	//序列化
	public static void Serialization(Elvis elvis){
		try{
			FileOutputStream fo = new FileOutputStream("serialObj.dat");
			ObjectOutputStream obj_o = new ObjectOutputStream(fo);
			obj_o.writeObject(elvis);
			obj_o.close();
		}catch(Exception e){
			e.printStackTrace();
		}
		System.out.println("已序列化的值elvis.data:"+elvis.getData());
	}
	
	//反序列化
	public static Elvis Deserialization(Elvis new_elvis)
	{
		try{
			FileInputStream fi = new FileInputStream("serialObj.dat");
			ObjectInputStream obj_i = new ObjectInputStream(fi);
			new_elvis = (Elvis)obj_i.readObject();
			System.out.println("恢复的值new_elvis.data:"+new_elvis.getData());
			//System.out.println("new_elvis.hashCode:"+new_elvis.hashCode());
			obj_i.close();
		}catch(Exception e)
		{
			e.printStackTrace();
		}
		return new_elvis;
	}
	
	
	public static void main(String args []){
		Elvis new_elvis = null;
		Elvis elvis = Elvis.getInstance();
		elvis.setData(5);
		Elvis elvis1 = Elvis.getInstance();
		System.out.println("elvis value: "+elvis1.getData());
		
		Serialization(elvis);
		new_elvis = Deserialization(new_elvis);
		System.out.println("\nelvis  hashCode: "+elvis.hashCode()+"\nelvis1 hashCode: "+elvis1.hashCode());
		System.out.println("new_elvis.hashCode:"+new_elvis.hashCode());
		
		
		if(new_elvis == elvis)
			System.out.println("\nnew_elvis == elvis");
		if(elvis == elvis1)
			System.out.println("elvis == elvis1");
		if(new_elvis == elvis1)
			System.out.println("new_elvis == elvis1");
	}
}

在有readResolve()方法情况下的输出:

Java 单例模式:使用私有构造函数强化singleton属性_第1张图片

 

而没有该方法的输出为:

Java 单例模式:使用私有构造函数强化singleton属性_第2张图片

 

在ObjectOutputStream类中的readUnshared()方法中有解释:

Java 单例模式:使用私有构造函数强化singleton属性_第3张图片

你可能感兴趣的:(Java)