• Category: behavioral
  • Type: object
  • Motivation: decouple client from receiver, keep maintaining the history of commands, e.g. undo/redo

diagram

// client
do {
    let receiver = Television()
    let invoker = RemoteControl()

    let turnOn = TurnOn(receiver)
    invoker.submit(turnOn)

    let turnOff = TurnOff(receiver)
    invoker.submit(turnOff)
}
// Receiver
class Television
{
    func turnOn()
    {
        print("turn on")
    }

    func turnOff()
    {
        print("turn off")
    }
}
// Invoker
class RemoteControl
{
    func submit(_ command: Command)
    {
        command.execute()
    }
}
// Command
protocol Command
{
    func execute()
}

class TurnOn: Command
{
    private let receiver: Television

    init(_ receiver: Television)
    {
        self.receiver = receiver
    }

    func execute()
    {
        receiver.turnOn()
    }
}

class TurnOff: Command
{
    private let receiver: Television

    init(_ receiver: Television)
    {
        self.receiver = receiver
    }

    func execute()
    {
        receiver.turnOff()
    }
}