Monday, March 26, 2007

Undo - Redo and Memento Pattern

How many times we have come across the problem of implementing undo/redo feature in course of software development? I reckon not many a times but ever wondered how to implement such a neat feature (like in office applications) in the software design.
Lo and Behold, the Memento Pattern is here to the rescue.

The idea is to encapsulate the state of an object in another object and hold its reference to be able to restore the object to original state when required. So if you have an object say A. Its state shall be represented by another object called B. Now when object A is to be modified to a new state the requesting object shall ask A for a state object, in this case called B and hold its reference. It will continue to change state of A. If an undo is required it simply resets the state of A by passing it back its original state B.
A detailed description with code example can be found here.
Another great resource on Memento is here and here

No comments: