M5 · Communication Between ObjectsSession 10-11BehavioralReshaped in KotlinOutline

Intent. Turn a request into an object so it can be queued, logged, and undone.

In Kotlin. A function reference covers the simple case; a data class earns its keep once you need an undo stack.

Turn a request into an object and queuing, logging, and undo come free. The comparison to hold is with Strategy: both wrap behavior in an object, but Strategy objectifies how something is done while Command objectifies the request itself – which is why only Command gives you an undo stack.

Structure

classDiagram
    class Command {
        <<interface>>
        +execute()
        +undo()
    }
    class ConcreteCommand {
        -receiver: Receiver
        -args
        +execute()
        +undo()
    }
    class Invoker {
        -history: List~Command~
        +run(c)
        +undoLast()
    }
    class Receiver {
        +action()
    }
    Command <|.. ConcreteCommand
    Invoker o--> Command : history
    ConcreteCommand o--> Receiver

Telling It Apart

Patterns whose structure looks the same but whose intent does not. See the Confusing Pairs reference.

  • Strategy — Encapsulate a family of algorithms as objects and swap them at runtime; the client picks.