Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Serialization Proxy Pattern? [duplicate]

Alas, Google has failed me...

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

like image 741
urig Avatar asked Mar 31 '09 18:03

urig


People also ask

What is proxy pattern in java?

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.

What problem does the proxy pattern solve?

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.

What does serializing mean in coding?

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.

What is serialization with example?

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.


1 Answers

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.

like image 57
Bob Carpenter Avatar answered Oct 05 '22 23:10

Bob Carpenter