Memento Design Pattern in Java

Memento Pattern is one of the behavioral patterns. Memento pattern is a software design pattern that provides the ability to restore state of an object to its previous state.

The memento pattern is implemented with three objects: the originator, a caretaker and a memento. The originator is an object that has an internal state. The caretaker asks the originator for a memento object. Then caretaker does something which make changes to the originator, but has the ability to undo the change. To roll back to the state before operations, it returns the memento object to the originator.

For more information please go to http://en.wikipedia.org/wiki/Memento_pattern

Example

The real life example would be when we write something to the notepad, wordpad etc. then we can undo the text or characters using ctrl+z in Windows Operating System.

Implementation

Create a Memento class which will track the state

Next create a class which will save to and restore from Memento

Now create a class to add objects to and get from Memento

Create a test class for testing the pattern

Output

That’s all. Thanks for your reading.

Soumitra

Software Professional, I am passionate to work on web/enterprise application. For more information please go to about me. You can follow on Twitter. You can be a friend on Facebook or Google Plus or Linkedin

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.