Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 667
Mr. Espresso Avatar asked Dec 28 '12 22:12

Mr. Espresso


People also ask

What is the purpose of Memento pattern?

The memento pattern allows one to capture the internal state of an object without violating encapsulation such that later one can undo/revert the changes if required. Here one can see that the memento object is actually used to revert the changes made in the object.

What is Memento pattern in Java?

Memento is a behavioral design pattern that allows making snapshots of an object's state and restoring it in future. The Memento doesn't compromise the internal structure of the object it works with, as well as data kept inside the snapshots.

What are different methods in serialization?

Serialization in Java is a mechanism of writing the state of an object into a byte-stream. It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies. The reverse operation of serialization is called deserialization where byte-stream is converted into an object.


1 Answers

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.

like image 97
Mike Q Avatar answered Sep 23 '22 22:09

Mike Q