Alas, Google has failed me...
What is the Serialization Proxy Pattern and where can I learn more about implementing and using it?
Proxy is a structural design pattern that provides an object that acts as a substitute for a real service object used by a client. A proxy receives client requests, does some work (access control, caching, etc.) and then passes the request to a service object.
The Proxy design pattern is one of the twenty-three well-known GoF design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.
Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed.
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With