Command pattern Created 2026-10-25 Updated 2026-10-31
Represent a request and the information needed to execute it as a software object with a common command interface. Undoable commands additionally retain enough information to invert their change: an insertion retains its position and value, a deletion retains the removed value, and a positional move retains the source and final destination indices.
For sequential undo/redo, a history manager stores applied commands on one stack and undone commands on another. Undo transfers the most recent applied command to the redo stack; redo transfers its head back after reapplying it. A fresh edit clears the redo branch. Command inverses are valid under this chronological protocol, not generally after unrelated intervening edits. Saving complete immutable versions instead gives a Memento pattern implementation of the same undo/redo interface.
Deep copy 2026-10-24
A copy that duplicates the relevant reachable mutable structure instead of sharing all original references. A Memento pattern snapshot containing mutable arrays must preserve their saved contents against subsequent mutation, whether by a suitable deep copy or by an immutable persistent representation. The intended ownership graph and any permitted sharing must be specified; blindly copying one outer object is only a shallow copy.
An undoable command records enough information to restore its input state when applied immediately after its corresponding edit. In a sequence, insertion at index is reversed by deletion at ; deletion is reversed by reinsertion of the saved value. If a move places an entry at final index after removing it from index , the inverse moves it from back to . Removing the moved entry recovers the original sequence with exactly that entry missing, which proves the inverse for both directions and for .
These local inverse identities extend to a history by applying inverses in reverse chronological order. A stack of completed commands and a stack of undone commands maintain that order. A fresh command invalidates the old redo branch. Arbitrary inverses after unrelated intervening edits need not satisfy the restoration identity. State snapshots in the Memento pattern supply a different way to realize the same chronological undo/redo contract.
If sequence versions are immutable, replace perform by the following method; the insert, delete and move entry points can stay as written:
private def perform(forward: () => Unit,
                    backward: () => Unit): Change = {
  val before = songs
  forward()
  val after = songs
  new Change {
    def undo(): Unit = { songs = before }
    def redo(): Unit = { songs = after }
  }
}
The unused inverse argument can subsequently be removed from perform and its callers. Each history record now captures two complete versions. Undo and redo restore the respective roots without replaying an operation, an instance of the Memento pattern. The same chronological history discipline still applies.
The supplied method signatures alone do not establish immutability or persistence. If insert or delete changes a shared mutable software object, merely storing its reference fails to freeze the earlier state. Then independent copies of the relevant state are needed, including any mutable song state intended to be undoable, or the implementation must provide immutable persistent data structure versions. This is a representation requirement, not a reason to invent a particular unavailable copying API.
Replace edit-specific inverse information by before/after snapshots implementing the Memento pattern. The same Change and History interfaces still work. A complete alternative suite is:
class SnapshotSlideSuite(initial: Sequence[Slide]) {
  private var slides = initial

  private def changeTo(after: Sequence[Slide]): Change = {
    val before = slides
    slides = after
    new Change {
      def undo(): Unit = { slides = before }
      def redo(): Unit = { slides = after }
    }
  }

  def insert(i: Int, x: Slide): Change =
    changeTo(slides.insert(i, x))

  def delete(i: Int): Change =
    changeTo(slides.delete(i))

  def move(from: Int, to: Int): Change = {
    val x = slides.elementAt(from)
    changeTo(slides.delete(from).insert(to, x))
  }
}
By-value evaluation computes after without changing slides, then changeTo captures the still-current before and installs the new value. The val bindings inside each call are stable snapshots, rather than later reads of a mutable variable. Under the same chronological history preconditions, undo and redo are constant-time reference assignments. This is the Memento pattern applied to an immutable sequence. Retaining a reference to an in-place-mutated sequence would not save its old state. The snapshot covers slide order and membership; it does not promise to undo unrelated mutations inside a Slide object.
The Memento pattern supports saving and later restoring an object's state while preserving encapsulation. The originator creates a snapshot and knows how to restore it; the memento stores that snapshot; the caretaker retains mementos and decides when to request restoration, without depending on their representation. Undo history is a typical use.
Scala's nested class in object-oriented programming definitions, access qualifiers, immutable values and path-dependent types help keep snapshots opaque and associated with their originator. For example:
final class Editor {
  private var text = ""
  final class Snapshot private[Editor] (
    private[Editor] val saved: String
  )
  def current: String = text
  def edit(next: String): Unit = { text = next }
  def save(): Snapshot = new Snapshot(text)
  def restore(s: Snapshot): Unit = { text = s.saved }
}

val editor = new Editor
editor.edit("first version")
val saved: editor.Snapshot = editor.save()
editor.edit("later version")
editor.restore(saved)
assert(editor.current == "first version")
The caretaker can retain saved but cannot inspect its private contents or construct an arbitrary snapshot. editor.Snapshot is a type tied to the stable editor value; a snapshot from a different Editor is not interchangeable without an explicit type escape. An immutable string is safe to share in this example. If the originator held mutable arrays or mutable nodes, storing only references to them would not freeze their contents; the memento would need a deep copy or a persistent immutable representation.[ref][ref]
Software design pattern 2026-10-24
A reusable organization of responsibilities and interactions for a recurring software-design problem. The Memento pattern separates snapshot creation/restoration from history management, while the Decorator pattern composes independent responsibilities behind one interface. A pattern specifies an arrangement rather than one mandatory class naming scheme.