Motivation: We want to parameterize objects with operations, queue or log operations, or support undoable operations, but the invoker shouldn’t know the details of what each operation does.
Intent: Encapsulate a request as an object, allowing parameterization, queuing, and undo support.
Here, each operation is self contained and can be stored, passed around, undone, etc. The invoker triggers command without really knowing anything.
interface Command {
fun execute()
fun undo()
}
// Concrete command
// TextEditor is the receiver class that provides insert/delete actions
class InsertTextCommand(
private val editor: TextEditor,
private val text: String,
) : Command {
override fun execute() { editor.insert(text) }
override fun undo() { editor.delete(text.length) }
}
// Helper class to manage command history
class CommandHistory {
private val history = mutableListOf<Command>()
fun execute(cmd: Command) { cmd.execute(); history.add(cmd) }
fun undo() { history.removeLastOrNull()?.undo() }
}