Introduction

Memento Design Pattern is a Behavioral design pattern. It offers a solution to implement undoable actions. Memento pattern is used to save and restore the previous state of an object without revealing the details of its implementation.

Intent

  • Capture the internal state of an object without violating encapsulation.
  • Providing a mean for restoring the object into initial state when needed.
  • Save checkpoints in application and restore back to those checkpoints later.

Implementation

Following are the participants in Memento Design Pattern

  • Originator : Object for which the state is to be saved. It knows how to create and save it’s state.
  • Caretaker : It keeps track of multiple mementos.
  • Memento : Maintain the state of Originator. It is written and read by the Originator. A memento must be in immutable object so that no one can change it’s state once created.

Originator can produce and consume a Memento, while Caretaker only keeps the state before restoring it.

UML of Memento Design Pattern
UML of Memento Design Pattern

Example

In this example, memento is created and restored for Article object.

public class Article 
{
  private String title;
  private String content;
     
  public Article(String title) {
    this.title = title;
  }
     
  //Create Memento     
  public ArticleMemento createMemento() 
  {
    ArticleMemento m = new ArticleMemento(title, content);
    return m;
  }
  
  // Restore Memento
  public void restore(ArticleMemento m) {
    this.title = m.getTitle();
    this.content = m.getContent();
  }

  @Override
  public String toString() {
    return "Article : Title=" + title + ", Content=" + content;
  }

  void setContent(String s){
    content = s;
  }
}

// Memento Class
public final class ArticleMemento
{
  private final String title;
  private final String content;
     
  public ArticleMemento(String title, String content) {
    this.title = title;
    this.content = content;
  }
 
  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 MementoTest 
{
  public static void main(String[] args) 
  {
    Article article = new Article("Article1");

    // Add Content
    article.setContent("Content");      
    System.out.println(article);
      
    // Create memento
    ArticleMemento memento = article.createMemento();
      
    // Update Content
    article.setContent("ContentChanged");
    System.out.println(article);
      
    // Restore
    article.restore(memento);
  }
}