The Memento pattern addresses the need to capture and restore an object's internal state without violating its encapsulation. This is useful in scenarios where you want to implement undo/redo functionality, allowing an object to revert to a previous state.
The Memento pattern involves three main components:
The originator creates a memento containing a snapshot of its current state. This memento can then be stored by the caretaker and used to restore the originator's state when needed.
A practical example of the Memento pattern is in text editors that offer undo/redo functionality. Each change to the document can be saved as a memento, allowing the user to revert to previous states of the document as needed.
Memento pattern in code:
// Originator public class Editor { private String content; public void setContent(String content) { this.content = content; } public String getContent() { return content; } public Memento save() { return new Memento(content); } public void restore(Memento memento) { content = memento.getContent(); } // Memento public static class Memento { private final String content; public Memento(String content) { this.content = content; } private String getContent() { return content; } } } // Caretaker public class History { private final Stack<Editor.Memento> history = new Stack<>(); public void save(Editor editor) { history.push(editor.save()); } public void undo(Editor editor) { if (!history.isEmpty()) { editor.restore(history.pop()); } } } // Client code public class Client { public static void main(String[] args) { Editor editor = new Editor(); History history = new History(); editor.setContent("Version 1"); history.save(editor); System.out.println(editor.getContent()); editor.setContent("Version 2"); history.save(editor); System.out.println(editor.getContent()); editor.setContent("Version 3"); System.out.println(editor.getContent()); history.undo(editor); System.out.println(editor.getContent()); history.undo(editor); System.out.println(editor.getContent()); } }
The above is the detailed content of Understanding the Memento Design Pattern in Java. For more information, please follow other related articles on the PHP Chinese website!