package com.neusoft.singleton.test;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class Singleton implements Serializable {
private static final long serialVersionUID = 5765648836796281035L;
public static final Singleton uniqueInstance = new Singleton();
private Singleton() {
}
// Remainder omitted
public static void main(String[] args) throws Exception {
// 序列化
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
new FileOutputStream("c:\\Singleton.clazz"));
Singleton singleton = Singleton.uniqueInstance;
objectOutputStream.writeObject(singleton);
objectOutputStream.close();
// 反序列化
ObjectInputStream objectInputStream = new ObjectInputStream(
new FileInputStream("c:\\Singleton.clazz"));
Singleton singleton2 = (Singleton) objectInputStream.readObject();
objectInputStream.close();
// 比较是否原来的实例
System.out.println(singleton == singleton2);
}
return uniqueInstance;
}
}
windows下测试通过
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamException;
import java.io.Serializable;
public class Singleton implements Serializable {
private static final long serialVersionUID = 5765648836796281035L;
public static final Singleton uniqueInstance = new Singleton();
private Singleton() {
}
// Remainder omitted
public static void main(String[] args) throws Exception {
// 序列化
ObjectOutputStream objectOutputStream = new ObjectOutputStream(
new FileOutputStream("c:\\Singleton.clazz"));
Singleton singleton = Singleton.uniqueInstance;
objectOutputStream.writeObject(singleton);
objectOutputStream.close();
// 反序列化
ObjectInputStream objectInputStream = new ObjectInputStream(
new FileInputStream("c:\\Singleton.clazz"));
Singleton singleton2 = (Singleton) objectInputStream.readObject();
objectInputStream.close();
// 比较是否原来的实例
System.out.println(singleton == singleton2);
}
/**
去掉此方法后singleton 不等于 singleton2,
加上此方法singleton 等于 singleton2。
*/
return uniqueInstance;
}
}
windows下测试通过