什么是序列化代理模式?[英] What is the Serialization Proxy Pattern?

本文是小编为大家收集整理的关于什么是序列化代理模式?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

a,Google使我失败了...

什么是序列化代理模式,我在哪里可以了解有关实施和使用的更多信息?

推荐答案

乔什·布洛赫(Josh Bloch)的最后一部分有一个很好的描述,有效的java ,第二版.

假设您有一个类A您想制作的序列化.您首先将其声明为实现Serializable.然后,您使用序列化方法writeReplace()返回所谓的"序列化代理",该代理将代替A实例. writeReplace()方法不需要公开. A上的默认序列化永远不会被调用,因此可以维护所有A的API适当位.

通常,代理被实现为私人静态嵌套类,本身必须实现Serializable(或Externalizable才能完全控制读/写过程).因为代理是私人的,所以它的实现细节(例如拥有no-arg构造函数和可变)将被隐藏.

代理存储足够的原始对象状态编写状态,以便可以在避难所重新构造对象.在避难所化时,代理使用方法readResolve()返回A的实例.对于单例,这可以是单身实例本身.

我写了一个详细的博客条目,其中包含示例,具有序列化代理的序列化不可或缺的单例.

本文地址:https://www.itbaoku.cn/post/627679.html

问题描述

Alas, Google has failed me...

What is the Serialization Proxy Pattern and where can I learn more about implementing and using it?

推荐答案

There's a nice description in the last section of Josh Bloch's Effective Java, Second Edition.

Suppose you have a class A that you would like to make serializable. You first declare it to implement Serializable. Then you use the serialization method writeReplace() to return a so-called "serialization proxy" that will be serialized in place of the instance of A. The writeReplace() method does not need to be public. The default serialization on A never gets invoked, so all of the API properites of A may be maintained.

Typically, the proxy is implemented as a private static nested class that itself must implement Serializable (or Externalizable for complete control of the read/write process). Because the proxy is private, its implementation details, such as having a no-arg constructor and being mutable, will be hidden.

The proxy stores enough of the state of the original object to write so that it can reconstitute the object on deserialization. On deserialization, the proxy uses the method readResolve() to return an instance of A. For singletons, this can be the singleton instance itself.

I wrote up a detailed blog entry with examples, Serializing Immutables and Singletons with a Serialization Proxy.