Design Patterns – Philosophy Behind the Memento Pattern

design-patterns

I have been reading up on memento pattern from various sources of the internet. Differing information from different sources has left me in confusion regarding why this pattern is actually needed.

The dofactory implementation says that the primary intention of this pattern is to restore the state of the system.

Wiki says that the primary intention is to be able to restore the changes on the system. This gives a different impact – saying that it is possible for a system to have memento implementation with no need to restore. And that ability of restore is a feature of this.

OODesign says that

It is sometimes necessary to capture the internal state of an object
at some point and have the ability to restore the object to that state
later in time. Such a case is useful in case of error or failure.

So, my question is why exactly do we use this one? Is it to save previous states – or to promote encapsulation between the Caretaker and the Memento? Why is this type of encapsulation so important?

Edit: For those visiting, check out this Implementation!

Edit: I am working in implementing a memento solution to my problem. I will post another question regarding that and link that question to this one. Thanks all for responding with valuable suggestions!

Edit 3: Here is the link to my sample implementation

Best Answer

A similar pattern, Memo, or Memoization, stores state as well, but it is often used as a program-speed optimization. If a time-consuming operation has a limited number of common inputs and outputs, the most common ones (or all of them) can be stored in a hashtable. When called again with the same inputs, it first checks the hashtable and if it finds them, it returns the previous output without recalculating it.

I imagine a Memento pattern could be used for performance as well - instead of doing all the reverse-calculations for a reverse state change, just restore from the previous state. Some functions are one-way, so there is no undo unless you store the previous state.

You could use a Memento pattern to memoize a periodic, or symmetric function like sine. Calculate all the values from 0-180 degrees, then go backwards through them to get the negative values from 180-360. Better yet, calculate values from 0-90, then go backwards through those values to get 90-180, forwards for 180-270, and backwards from 270-360.

Ctrl-Z in Word, or the undo function of any software is likely implemented by using the memento pattern, or in some cases, possibly by a reverse of the function that made each change. In the second case, the history of which functions were called would be mementos, so I suppose the memento pattern is always used for undo.

Related Topic