Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Implement undo for a text editor with the memento pattern in Java, and explain why the memento should not expose the editor's internals.

With the memento pattern, the editor (the originator) creates an immutable snapshot of its state with save(), a record such as EditorMemento(String text, int cursor), and can return to it with restore(memento). A caretaker, such as a history object holding a Deque of mementos, stores and hands back snapshots without ever reading their contents, and it caps the number kept so memory stays bounded. The memento should not expose the editor's internals because that would let other classes depend on or change the editor's private representation, which breaks encapsulation and makes every internal change a breaking change.

Why this question is asked

Undo is one of those features users take for granted and developers underestimate. The memento pattern is the classic way to implement it, and interviewers ask for it because it combines a small piece of working code with a real design principle: encapsulation. Writing the code is easy; writing it so that the history class cannot poke at the editor's internals is the part that shows experience. In this answer, we will recap the three roles of the pattern, write an editor with save and restore, build a bounded undo history, see how to keep the memento opaque to everyone except the editor, and talk about immutability.

1A Quick Recap of the Three Roles

The pattern has three roles. The originator is the object whose state we want to snapshot, here the editor with its text and cursor position. The memento is the snapshot, a small object holding a copy of that state at one moment. The caretaker is whoever keeps the mementos and decides when to restore one, here the undo history. The rule that makes it a pattern rather than just copying fields is that only the originator creates mementos and reads what is inside them. The caretaker treats them as sealed envelopes.

2The Editor and Its Memento

We start with an editor that holds a StringBuilder and a cursor. The memento is a record, which gives us an immutable class with two final fields in one line. To keep it opaque, the record is private and nested inside Editor, and the outside world only sees a public marker interface called Snapshot.

Java
public final class Editor {
public interface Snapshot {} // what the caretaker sees: nothing
private record EditorMemento(String text, int cursor) implements Snapshot {}
private final StringBuilder text = new StringBuilder();
private int cursor;
public void type(String s) {
text.insert(cursor, s);
cursor += s.length();
}
public void moveCursor(int position) {
cursor = Math.max(0, Math.min(position, text.length()));
}
public Snapshot save() {
return new EditorMemento(text.toString(), cursor); // toString() copies the characters
}
public void restore(Snapshot snapshot) {
if (!(snapshot instanceof EditorMemento m)) {
throw new IllegalArgumentException("snapshot was not created by an Editor");
}
text.setLength(0);
text.append(m.text());
cursor = m.cursor();
}
public String text() { return text.toString(); }
}

Notice three details. save() copies the text with toString(), so later typing into the StringBuilder cannot change a memento that was already taken. restore() uses a pattern match to get back the private record, so the editor can read its own snapshots, while any other code that receives a Snapshot has no type to cast to and no accessors to call. And the editor checks that the snapshot is really one of its own, which protects against a caller passing some other Snapshot implementation.

3The Caretaker: A Bounded Undo History

The history keeps a stack of snapshots, newest first. Before each edit, the application asks the editor for a snapshot and pushes it. Undo pops the newest snapshot and gives it back to the editor. An ArrayDeque used as a stack gives us push and pop at the front in constant time, and we drop the oldest entry from the back once we reach the limit.

Java
public final class History {
private final Deque<Editor.Snapshot> undo = new ArrayDeque<>();
private final int limit;
public History(int limit) { this.limit = limit; }
public void record(Editor.Snapshot s) {
undo.push(s); // newest at the front
if (undo.size() > limit) {
undo.removeLast(); // forget the oldest, memory stays bounded
}
}
public Optional<Editor.Snapshot> undo() {
return Optional.ofNullable(undo.poll());
}
}
Editor editor = new Editor();
History history = new History(100);
history.record(editor.save()); editor.type("Hello");
history.record(editor.save()); editor.type(", world");
System.out.println(editor.text()); // Hello, world
history.undo().ifPresent(editor::restore);
System.out.println(editor.text()); // Hello
history.undo().ifPresent(editor::restore);
System.out.println(editor.text()); // (empty)
history.undo().ifPresent(editor::restore); // nothing left, no change
Step throughUndo with the memento pattern
User actionHistory (caretaker)Editor (originator)
before typing: save()
Snapshot (opaque)
push snapshot, drop oldest above 100
type(", world")
undo()
restore(newest snapshot)
read its own private record, reset text and cursor

7 messages in order. Play them, or step through them one at a time.

Only the editor ever looks inside a snapshot.

The History class never looks inside a snapshot. It could not even if it wanted to, because Editor.Snapshot has no methods. That is the caretaker role exactly: it decides when, the originator decides what.

The limit matters more than it looks. Each memento here holds a full copy of the text, so a 1 MB document with an unlimited history of 5,000 edits would keep up to 5 GB of copies. With a limit of 100, the worst case is about 100 MB, and the oldest edits simply cannot be undone. Real editors also merge small edits, for example all characters typed within a second, into one undo step, which reduces the number of snapshots.

4Why the Memento Must Not Expose the Editor's Internals

Suppose we had made the memento a public record, public record EditorMemento(String text, int cursor). Records have public accessors, so any class could now read memento.text() and memento.cursor(). That sounds harmless until we see what follows. The history might start displaying the text of each undo step, a spell checker might read old mementos, and a test might build mementos by hand. All of them now depend on the editor storing exactly a string and an int. When the editor later changes its representation, for example to a rope data structure with several cursors, every one of those classes breaks.

Worse, if a memento exposed mutable internals, such as the StringBuilder itself, other code could change a snapshot after it was taken, and undo would restore a state that never existed. So encapsulation here protects two things: the freedom to change the editor's internals, and the integrity of history. A package-private record is a lighter alternative when the caretaker lives in another package, since that package cannot read the accessors, but a private nested record with a public marker interface is the strictest form.

5Keeping Mementos Immutable

A memento must describe one moment and never change. Records help because their fields are final, but final only protects the reference. If the editor also kept a list of formatting spans, a record holding that list would still point at the editor's live list, and later edits would leak into old snapshots. The fix is to copy mutable fields when creating the memento, for example with List.copyOf(spans), which returns an unmodifiable copy. Strings and ints are already immutable, which is why our two-field memento needed only the toString() copy.

6Follow-up questions

How would you add redo?

Keep a second deque for redo. When the user undoes, the application first saves the current state and pushes it onto the redo stack, then restores the undo snapshot. Redo does the reverse. Any new edit clears the redo stack, because the redo history no longer matches the document. Both stacks respect the size limit.

Is copying the whole text on every edit too expensive?

For small documents it is fine and very simple. For large documents, editors store commands with inverse operations, such as inserted these characters at position 40, or use persistent data structures that share unchanged parts between versions. Those trade simplicity for memory, which is a separate design question.

Could Editor implement Cloneable and use clone() as the memento?

It could, but clone() exposes the whole editor rather than a narrow snapshot, copies shallowly by default so mutable fields would be shared, and gives the caretaker a full Editor it could call methods on. A dedicated immutable memento type is clearer and safer.

7Conclusion

In this answer, we implemented undo with the memento pattern. The editor is the originator: save() returns an immutable EditorMemento record with a copy of the text and the cursor, and restore() reads it back. The History class is the caretaker: it keeps snapshots in a Deque, never reads them, and drops the oldest once it reaches its limit so memory stays bounded. We kept the record private behind a public Snapshot interface, so no other class can depend on or alter the editor's internals, and we copy mutable fields so snapshots never change after they are taken.

What to say in the interviewAbout 90 seconds aloud

Open with

The memento pattern has three roles. The editor is the originator, the snapshot is the memento, and the undo history is the caretaker. I would model the memento as a record, EditorMemento with the text as a String and the cursor as an int, and give the editor save, which returns a new memento with a copy of the current text, and restore, which takes one and resets the text and cursor.

Then, if they want more

The history keeps a Deque of mementos used as a stack. Before every edit, the application pushes editor.save, and undo pops the newest and passes it to editor.restore. The history never reads what is inside; it only decides when to save and restore.

I would also cap the history, say at 100 entries, dropping the oldest, because each memento is a full copy and an unlimited history of a large document can use gigabytes. On encapsulation, I keep the record private and nested inside Editor, implementing a public marker interface, so the caretaker can hold snapshots but has no accessors to call.

If the memento exposed the internals, other classes would start depending on the editor's representation, and changing it later would break them, or they could even change history. Finally the memento must be immutable, so any mutable field like a list gets copied with List.copyOf when the snapshot is taken.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Implement undo for a text editor with the memento pattern in Java, and explain why the...": https://scrivio-interview-library.netlify.app/java/behavioral-patterns/24da1b6102/