Search code examples
javadesign-patternsserializationmemento

Difference between Memento Pattern and Serialization


I am doing some research into the Memento Pattern and I am generally new to behavioural patterns and with my research I have been getting pretty confused. One of the main things I have been getting confused on is the differences between the Memento Pattern and Serialization.

From what I can gather both can be used to store objects and have them brought back at a later date but I have not been able to find a clear cut answer on what the key differences between them are, maybe I have missed something in my research but I was wondering if anyone could shed some light on what the differences are between the two.

Thanks


Solution

  • Typically the Memento pattern is used to implement roll-back/save point support. For example I might want to mark the state of an object at a point in time, do some work and then decide to revert that object back to the point at which is was marked.

    The implementation of a Memento pattern could use serialisation, which would involve saving the contents of the object into a byte[] and keeping in memory or writing to disk. When reverting the content of the object would be rebuilt from the serialised copy.

    Conversely I could implement a Memento pattern by cloning the object in memory and keeping a reference to the copy and then copying the state back if the object needs reverting. This method doesn't use serialisation.