Motivation: We want to capture snapshots of an object’s state so that we can restore it to a previous state later (e.g., undo/redo functionality).
Intent: Capture and externalize an object’s internal state without violating encapsulation, so the object can be restored to that state later.
See Leetcode - Snapshot Array?
class Editor(var text: String) {
fun save(): Snapshot = Snapshot(text)
fun restore(snapshot: Snapshot) { text = snapshot.state }
class Snapshot(val state: String)
}
class History {
private val snapshots = mutableListOf<Editor.Snapshot>()
fun push(snapshot: Editor.Snapshot) { snapshots.add(snapshot) }
fun pop(): Editor.Snapshot? = snapshots.removeLastOrNull()
}