Serializing object pointers requires a method of uniquely identifying objects. The identifier of the object that is being referenced is saved in the serialization process. This identifier is used to recreate the pointer to the object when the web of objects is recreated in memory. Typically, each saved object is given an ID, and these IDs are stored instead of the pointer. This also solves the issue of objects that are referenced by multiple pointers — only one copy of these objects should be created when the web of objects is recreated in memory.
The use of these IDs guarantees that if two objects are pointing at the same third object before they were serialized, then they will point at the same (recreated) third object when they are recreated. Using the IDs instead of pointers also allows the serialized objects to be recreated in an environment different from the one in which they were serialized, which can be very important in distributed systems. An example of this is support for load balancing — objects can be moved in a way that is transparent to the objects that point to them.
The Serializer Pattern decouples the application code from the reading and writing responsibilities. On the other hand, each time a new class is defined it must inherit from the
class and implement the read and write methods.Serializable
The Serializer Pattern also undermines encapsulation by allowing access to the object's internal state. This can be solved with yet another design pattern, the Memento Pattern, described in the Design Patterns book by Gamma et al. (Addison-Wesley, ISBN 0-201-63361-2).
The Memento (or Token) Pattern is used to create an external representation of the internal state of an object, so that the state of the object can be persisted without violating encapsulation. A
object is created, which stores the internal state of the original object, so that it may be restored at a later time. A memento
object holds the caretaker
, then provides it back to the original object so that it can restore its previous state. The memento
, however, cannot access or alter the data held by the caretaker
. This extra level of indirection allows the original object to keep its internal state hidden from the reader and writer, but at the cost of some extra overhead.memento
The
itself must be memento
in this particular usage of the Memento Pattern. If the serializable
uses non-primitive data to capture the state of the object, this can mean a second recursive level of memento
s and memento
objects, adding complexity.serializable