Memento Design Pattern

Memento design pattern is behavioral pattern and one of 23 design patterns discussed by Gang of Four. Memento pattern is used to restore state of an object to a previous state. It is also known as snapshot pattern.

A memento is is like a restore point during the life cycle on the object, which the client application can use to restore the object state to its state. Conceptually, it is very much like we create restore points for operating systems and use to restore the system if something breaks or system crashes.

The intent of memento pattern is to capture the internal state of an object without violating encapsulation and thus providing a mean for restoring the object into initial state when needed.

1. When to use memento design pattern

Memento pattern shall be be used in any application in which object’s state is continuously changing and the user of the application may decide to rollback or undo the changes changes at any point.

A memento can also be used in applications which must be restarted from their last known working state or draft. An example of this can be an IDE which restart from changes, user made before closing the IDE.

2. Real world example of memento pattern

  • In a GUI editor (e.g. MS Paint), we can keep making changing to drawing and we can rollback the changes with simple commands like CTRL + Z.
  • In code editors, we can revert or apply any code change with simple commands to undo and redo.
  • In calculator applications, we can revisit all the calculations in memory with simple button press.
  • In programming, memento can be used to create checkpoints during database transactions. If any operation fails, we just rollback everything to last known stable database state.
  • javax.swing.text.JTextComponent class provides an undo support mechanism. javax.swing.undo.UndoManager can act as a caretaker, an implementation of javax.swing.undo.UndoableEdit can act like a memento, and an implementation of javax.swing.text.Document can act like an originator.

3. Memento design pattern

3.1. Architecture

Memento Design Pattern
Memento Design Pattern

Image Credit – Wikipedia

3.2. Design participants

The memento pattern has three participants.

  1. Originator – is the object that knows how to create and save it’s state for future. It provides methods createMemento() and restore(memento).
  2. Caretaker – performs an operation on the Originator while having the possibility to rollback. It keeps track of multiple mementos. Caretaker class refers to the Originator class for saving (createMemento()) and restoring (restore(memento)) originator’s internal state.
  3. Memento – the lock box that is written and read by the Originator, and shepherded by the Caretaker. In principle, a memento must be in immutable object so that no one can change it’s state once created.

4. Memento design pattern example

In this example, we are creating memento for an Article object which has three basic attributes – id, title and content. ArticleMemento class is used as memento for Article objects.

public class Article 
{
	private long id;
	private String title;
	private String content;
	
	public Article(long id, String title) {
		super();
		this.id = id;
		this.title = title;
	}
	
	//Setters and getters
	
	public ArticleMemento createMemento() 
	{
		ArticleMemento m = new ArticleMemento(id, title, content);
		return m;
	}
	
	public void restore(ArticleMemento m) {
		this.id = m.getId();
		this.title = m.getTitle();
		this.content = m.getContent();
	}

	@Override
	public String toString() {
		return "Article [id=" + id + ", title=" + title + ", content=" + content + "]";
	}
}
public final class ArticleMemento 
{
	private final long id;
	private final String title;
	private final String content;
	
	public ArticleMemento(long id, String title, String content) {
		super();
		this.id = id;
		this.title = title;
		this.content = content;
	}

	public long getId() {
		return id;
	}

	public String getTitle() {
		return title;
	}

	public String getContent() {
		return content;
	}
}

The Main class is acting as Caretaker which creates and restores the memento objects.

public class Main 
{
	public static void main(String[] args) 
	{
		Article article = new Article(1, "My Article");
		article.setContent("ABC");		//original content
		System.out.println(article);
		
		ArticleMemento memento = article.createMemento();	//created immutable memento
		
		article.setContent("123");		//changed content
		System.out.println(article);
		
		article.restore(memento);		//UNDO change
		System.out.println(article);	//original content
	}
}

Program Output.

Article [id=1, title=My Article, content=ABC]
Article [id=1, title=My Article, content=123]
Article [id=1, title=My Article, content=ABC]

5. FAQs

5.1. Memento as inner class?

The memento design pattern can be implemented in many different ways such as inner classes, package-private visibility or serialization etc. There is no fixed guideline for implementing the memento pattern.

5.2. Benefits of memento pattern

  • The biggest advantage is that you can always discard the unwanted changes and restore it to an intended or stable state.
  • You do not compromise the encapsulation associated with the key objects that are participating in this model.
  • Maintains high cohesion.
  • Provides an easy recovery technique.

5.3. Challenges of memento pattern

  • A high number of mementos require more storage. At the same time, they put additional burdens on a caretaker.
  • It also increases maintenance costs in parallel because code efforts needs to be made to manage memento classes as well.
  • The additional time to save the states decreases the overall performance of the system.

Drop me your questions related to memento pattern in comments.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

2 thoughts on “Memento Design Pattern”

  1. Hi!
    Nice article but it doesn’t show the real importance of memento, which is returning to any previous state. this will only return to the last previous state.
    another better approach is to maintain a stack in the care taker class that saves every memento object

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.