If you have worked on a document such as a contract, specifications or a thesis, you were probably glad that your text editor (e.g. Microsoft Office) saved your work regularly and kept a few versions somewhere. That’s the idea of the memento pattern. It allows an object to keep a token representing a state of that object.
Let’s see how the code would look like if we want to have our text editor saving versions.
public class TextEditor {
// for the sake of simplicity,
// we use a string to represent the content
private String content;
public void write(String content) {
this.content = content;
}
public void append(String newContent) {
this.content += newContent;
}
}
Now we want to create a memento that will keep versions of our content:
public class Version {
private String content;
// the version is read only. We set the content
// when we create the version.
public Version(String content) {
this.content = content;
}
public String getContent() {
return content;
}
}
The TextEditor class needs a new method to save and restore a version:
public class TextEditor {
private String content;
public void write(String content) {
this.content = content;
}
public void append(String newContent) {
this.content += newContent;
}
public Version save() {
return new Version(content);
}
public void restore(Version v) {
this.content = v.getContent();
}
}
The code that uses the text editor looks like:
public class Application {
public static void main(String[] args) {
TextEditor editor = new TextEditor();
editor.write("this is my first version.");
Version v1 = editor.save();
editor.append("I am adding a second version");
Version v2 = editor.save();
// restore version 1
editor.restore(v1);
// content = "this is my first version."
// restore version 2
editor.restore(v2);
// content = "this is my first version.I am adding a second version"
}
}
The main inconvenient to this pattern is the use of memory. If memory is an issue, we may want to use the command pattern which saves commands instead of states (so less memory though more complex handling of the state).