Monday, August 2, 2010

Memento Pattern

This is one of the Behavioral pattern and also known as Token or SnapShot Pattern. The purpose of this pattern is to preserve a snapshot of an object's state, so that object can return to its original state without having to reveal its contents to the rest of the world. A better approach is to use an object to contain the data to be stored. You could this object to recreate the original. Other objects would not be able to read or modify the data, since the data to be stored would be encapsulated. The object is used as a 'Souvenir' that only has value to the original holder and helps to remember its previous state.
Use Memento when all of the following apply:
  •     A snapshot of the state of an object should be taken.
  •     That snapshot is used to recreate the original state.
  •     A direct interface to the object to read its internal state would violate its encapsulation, because this would also reveal the internal workings.
A Memento is an object that contains the current internal state of the Originator object. Only the Originator can store and retrieve information from the Memento. To the outside world the Memento is just an arbitrary object. The Memento pattern is like a credit card. Although you don’t know what is actually really on the card, you know what it provides (lots of buying power to buy lots of toys). In the Memento’s case, it allows you to preserve and restore the state.
 
Because the Memento should be accessible only to the Originator, it is best to make the Memento a public inner class in the Originator. All the methods are declared private so they are only available to the Memento and its enclosing class, thus providing the appropriate encapsulation.
 
Instances of an inner class are always associated with an instance of the outer class. This is necessary because an inner class always has access to instance variables of the outer class. That causes a problem in this situation; the Memento should be independent of a specific instance of an Originator. Therefore the Memento class needs to be a static inner class.
 
Memento objects can become very large, especially if the Originator keeps all its state in the Memento and Mementos are created frequently. To compensate for this, you can change Mementos so that they record only changes in state since the previous creation of a Memento. The state holder has to keep track of the order of the Mementos. Job promotions are an example of when you might apply this. After every promotion your employee benefits and salary are changed based on the previous salary, and you may get a new boss, new department or a bigger car. Now every Memento of your employee benefits only needs to record the increase or decrease in conditions/salaries since the last Memento.

No comments: