Design patterns in examples - Memento

Design patterns in examples - Memento

Design patterns in examples - Memento

Memento is a design pattern that represents one of the possibilities to implement save and restore functionality.

The pattern consists of the following elements:

Memento is an interface that represents an object that can be saved and restored but it exposes only choses properties without revealing details.

  // Memento
public interface MailMemento {
}

 

Originator is a class that knows details of Memento because actual implementation of Memento (Draft in this case) is an inner class of it. It exposes methods to create a Memento (createDraft()) and to restore it (load(MailMemento mailMemento)).

 // Originator
public class MailEditor {
private String content;

public MailMemento createDraft() {
return new Draft(content);
}

public void load(MailMemento mailMemento) {
content = ((Draft) mailMemento).content;
}

public void setContent(String content) {
this.content = content;
}

private static class Draft implements MailMemento {
private final String content;

private Draft(String content) {
this.content = content;
}
}
}

 

Caretaker is a class that operates on Memento, for example can store and restore it but it has a limited access to Memento's properties as it accesses it via the interface only.

 // Caretaker
public class MailBox {
private MailMemento draft;

public void save(MailMemento mailMemento) {
draft = mailMemento;
}

public MailMemento loadDraft() {
return draft;
}
}

 

Memento pattern can be used by other code in the following way.

public class Main {
public static void main(String[] args) {
MailBox mailBox = new MailBox();

MailEditor mailEditor = new MailEditor();
mailEditor.setContent("body");
MailMemento draft = mailEditor.createDraft();
mailBox.save(draft);

MailMemento restoredDraft = mailBox.loadDraft();
mailEditor.load(restoredDraft);
}
}

 

Do not miss valuable content. You will receive a monthly summary email. You can unsubscribe anytime.

 

If you like what I do, consider buying me a coffee :)

Buy me a coffeeBuy me a coffee