// (1) 创建单例类
import com.cst.singleton.demo1.Singleton1;
import java.io.Serializable;
/**
* 静态内部类实现懒汉式单例对象.
*/
public class Singleton4 implements Serializable {
/**
* 将类的构造方法私有化,防止外部类通过Singleton4构造方法获取实例
*/
private Singleton4() {
}
/**
* 静态内部类调用的时候加载一次
*/
private static class SingletonHolder{
private static final Singleton4 INSTANCE=new Singleton4();
}
/**
* 返回创建的单例对象
* @return
*/
public static Singleton4 getInstance(){
return SingletonHolder.INSTANCE;
}
// 该方法,可以确保反序列化时返回的是同一个单例对象。
protected Object readResolve() {
return getInstance();
}
}
// (2) 创建客户端测试类
public class Client {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Singleton4 instance = Singleton4.getInstance();
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("StaticInstance"));
// 写入到磁盘
outputStream.writeObject(instance);
// 关闭输出流
outputStream.close();
// 反序列化
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("StaticInstance"));
Singleton4 instanceTarget =(Singleton4) inputStream.readObject();
inputStream.close();
System.out.println("instance 是否等于反序列化获取的对象 StaticInstance: "+(instance==instanceTarget));
}
}