NOTE
Memento Pattern
Memento-pattern notes showing how to save an object's state and restore it later.
This is a historical learning note and may contain outdated or incomplete understanding.
1. Definition
Save an object’s state so it can be restored later. Undo logic such as Ctrl+Z can use this pattern.
2. UML
3. Java
3.1. Object Being Saved
public class Article
{
private String title;
private String content;
public Article(String title, String content)
{
this.title = title;
this.content = content;
}
public String getTitle()
{
return title;
}
public void setTitle(String title)
{
this.title = title;
}
public String getContent()
{
return content;
}
public void setContent(String content)
{
this.content = content;
}
public ArticleMemento saveToMemento()
{
return new ArticleMemento(this.title, this.content);
}
public void undoFromMemento(ArticleMemento memento)
{
this.title = memento.getTitle();
this.content = memento.getContent();
}
@Override
public String toString()
{
return "Article{" + "title='" + title + '\'' + ", content='" + content + '\'' + '}';
}
}
3.2. Memento
- ArticleMemento
public class ArticleMemento
{
private String title;
private String content;
public ArticleMemento(String title, String content)
{
this.title = title;
this.content = content;
}
public String getTitle()
{
return title;
}
public String getContent()
{
return content;
}
}
- ArticleMementoManager
public class ArticleMemento
{
private String title;
private String content;
public ArticleMemento(String title, String content)
{
this.title = title;
this.content = content;
}
public String getTitle()
{
return title;
}
public String getContent()
{
return content;
}
}
3.3. Client
public class Client
{
public static void main(String[] args)
{
Article article = new Article("Title 1", "Content 1");
System.out.println("Initially: " + article);
ArticleMemento articleMemento = article.saveToMemento();
ArticleMementoManager mementoManager = new ArticleMementoManager();
mementoManager.addMemento(articleMemento);
article.setContent("Content 2");
article.setTitle("Title 2");
System.out.println("After modification: " + article);
ArticleMemento memento = mementoManager.getMemento();
article.undoFromMemento(memento);
System.out.println("Restored from memento: " + article);
}
}
Discussion
Sign in with GitHub to comment. Discussions are stored as GitHub Issues.View on GitHub