Sitemap
Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.

Command Design Pattern

The Command Design Pattern encapsulates a request as an object, allowing you to parameterize other objects with different requests, queue them, and log or undo operations easily. This pattern turns commands into standalone objects, making it easier to handle complex sequences of operations and enabling more flexible, decoupled code.

7 min readNov 5, 2024

--

Complexity: ⭐️★★
Popularity: ⭐️⭐️⭐️

The Problem Command Solves

Imagine your team are building a photo editing application like Adobe Lightroom or PhotoShop. And your task is to create a Word like toolbar with bunch of buttons for various operations. You can either create a top hierarchical Button class or use generic button as well.

Press enter or click to view image in full size
All buttons are derived from the defined Button object.

You have multiple buttons performing different actions, each button might need to have its own unique click handler. The simplest but inflexible solution would be to create a separate subclass for each action the button could perform.

Press enter or click to view image in full size
Subclasses of Button

We're directing to the wrong way. A lots lots of subclasses… What about when i want to change the base Button class? This might break the code in subclasses. And also GUI code has become awkwardly dependent on the volatile code on the business logic-side. Some operations, such as copy-pasting would need to be invoked multiple places. It is okey to subclassing Button again for now, but later decided to implement Menus, Shortcuts etc., need to duplicate this code in multiple places. This is getting out of control.

The Command Solution

Software architecture thrives on clean separation of concern, with each layer serving a distinct purpose. Most modern applications implement this through a clear division between presentation and processing — specifically, separating the user interface layer from the business logic core. The UI layer excels at its specialized role: managing visual elements, handling user interactions, and orchestrating the flow of information across the screen. Yet when computational tasks arise, whether it’s data analysis, business rule validation, or complex algorithmic processing, this presentation layer steps aside, delegating these operations to the dedicated business logic layer.

A GUI objects calls a method of business logic object and pass it some arguments. This process usually describes as one object sending another a request.

Get Ahmet Tarik DÖNER’s stories in your inbox

Join Medium for free to get updates from this writer.

The command pattern suggests that GUI objects shouldn’t send these request directly. Instead, you should extract all of these request details, such as the object being called, the name of the method and the list of arguments into a separate command class with a single method triggers this request

Press enter or click to view image in full size
Accessing the business logic via a command.

Next step make commands implement same interface. Usually, it has just a single execution method that takes no parameters. This interface lets you use various commands with the same request sender. Since the command execution method doesn’t have any parameters, how we pass the request details to the receiver? The answer is either the command should be pre-configured with this data, or capable of getting it on its own.

Press enter or click to view image in full size
GUI objects delegates the work to commands.

Back to our app, we no longer all those subclasses to implement various click behaviors. Just put a single field to stores a reference to a command object and make the button execute that command on a click

The Command Structure

Press enter or click to view image in full size
The Structure of Command.

Domain of Applicability

  • To parameterize objects with operations: Command pattern lets you convert method calls into standalone objects, making it possible to pass commands as arguments, store them, or even switch them at runtime.
  • To queue, schedule, or remotely execute operations: Since commands can be serialized (converted to strings), they can easily be stored in files or databases, queued, or executed later.
  • To implement undoable actions: The Command pattern enables reversing actions by storing necessary details, making it ideal for undo/redo functionality.

How does the Command Implements:

  1. Define a command interface with a single execute() method.
  2. Create concrete command classes that implement this interface. Each command class should store request-specific details, including any necessary arguments and a reference to the target receiver object, initialized through the command’s constructor.
  3. Identify sender classes and add fields for storing command objects. These senders should interact with commands only through the command interface, without creating command objects directly.
  4. Update senders to execute commands rather than directly calling methods on the receiver.
  5. Initialize the command chain in the following order:
  • Create receiver objects.
  • Create command objects, associating them with the appropriate receivers.
  • Create sender objects and assign specific commands to them.

Conceptual Example


// MARK: - Command Interface
/// The Command interface declares a method for executing a command.
protocol Command {
func execute()
}

// MARK: - Concrete Commands
/// Some commands can implement simple operations on their own.
final class SimpleCommand: Command {

private var payLoad: String

init(_ payLoad: String) {
self.payLoad = payLoad
}

func execute() {
print("SimpleCommand: See, I can do simple things like printing (" + payLoad + ")")
}
}

/// However, some commands can delegate more complex operations to other objects
/// called 'receivers'.
final class ComplexCommand: Command {

private var receiver: Receiver

/// Complex commands can accept one or several receiver objects along with any
/// context data via the constructor.
private var a: String
private var b: String

init(receiver: Receiver, _ a: String, _ b: String) {
self.receiver = receiver
self.a = a
self.b = b
}

/// Commands can delegate to any methods of a receiver.
func execute() {
print("ComplexCommand: Complex stuff should be done by a receiver object.\n")
receiver.doSomething(a)
receiver.doSomethingElse(b)
}
}

// MARK: - Receiver
final class Receiver {
func doSomething(_ a: String) {
print("Receiver: Working on (" + a + ")\n")
}

func doSomethingElse(_ b: String) {
print("Receiver: Also Working on (" + b + ")\n")
}
}


// MARK: - Sender / Invoker
/// The Invoker class is associated with one or several commands. It sends a request to the command.
final class Invoker {
private var onStart: Command?
private var onFinish: Command?

/// Initialize commands
func setOnStart(_ command: Command) {
onStart = command
}

func setOnFinish(_ command: Command) {
onFinish = command
}

/// The Invoker does not depend on concrete command or receiver classes. The
/// Invoker passes a request to a reciever indirectly, by executing a command.
func doSomethingImportant() {
print("Invoker: Does anybody want something done before I begin?")
onStart?.execute()
print("Invoker: ...doing something really important...")
print("Invoker: Does anybody want something done after I finish?")
onFinish?.execute()
}
}

class TestCommandConceptual {
func test() {
/// The Client code can parametirize an invoker with any commands.
let invoker = Invoker()
invoker.setOnStart(SimpleCommand("Say 🙋"))
let receiver = Receiver()
invoker.setOnFinish(ComplexCommand(receiver: receiver, "Send email📧", "Save reports"))
invoker.doSomethingImportant()
}
}

let test = TestCommandConceptual()
test.test()

Real World Example

import Foundation

class DelayedOperation: Operation {

private var delay: TimeInterval
private var _executing: Bool = false
private var _finished: Bool = false

init(_ delay: TimeInterval) {
self.delay = delay
}

override var isExecuting: Bool {
get { _executing }
set {
willChangeValue(forKey: "isExecuting")
_executing = newValue
didChangeValue(forKey: "isExecuting")
}
}

override var isFinished: Bool {
get { _finished }
set {
willChangeValue(forKey: "isFinished")
_finished = newValue
didChangeValue(forKey: "isFinished")
}
}

override func start() {
guard delay > 0 else {
_start()
return
}
let deadline = DispatchTime.now() + delay
DispatchQueue(label: "").asyncAfter(deadline: deadline) {
self._start()
}
}

func _start() {
guard !self.isCancelled else {
print("\(self): operation is cancelled.")
self.isFinished = true
return
}
self.isExecuting = true
self.main()
self.isExecuting = false
self.isFinished = true
}
}

final class WindowOperation: DelayedOperation {
override var description: String { "WindowOperation" }

override func main() {
print("\(self): Windows are closed via HomeKit.")
}
}

final class TaxiOperation: DelayedOperation {
override var description: String { "TaxiOperation" }

override func main() {
print("\(self): Taxi is ordered via Uber.")
}
}

final class DoorOperation: DelayedOperation {
override var description: String { "DoorOperation" }

override func main() {
print("\(self): Door are closed via HomeKit.")
}
}


final class SiriShortCuts {
static let shared = SiriShortCuts()
private lazy var queue = OperationQueue()

private init() { }

enum Action: String {
case leaveHome
case leaveWork
}

func perform(_ action: Action, delay: TimeInterval = 0) {
print("Siri: performing \(action)-action\n")
switch action {
case .leaveHome:
add(operation: WindowOperation(delay))
add(operation: DoorOperation(delay))
case .leaveWork:
add(operation: TaxiOperation(delay))
}
}

private func add(operation: Operation) {
queue.addOperation(operation)
}

private func cancelOperation(with operationType: Operation.Type) {
queue.operations.filter { operation in
return type(of: operation) == operationType
}.forEach { $0.cancel() }
}

func cancel(_ action: Action) {
print("Siri: cancelling \(action)-action")
switch action {
case .leaveHome:
cancelOperation(with: WindowOperation.self)
cancelOperation(with: DoorOperation.self)
case .leaveWork:
cancelOperation(with: TaxiOperation.self)
}
}
}

import XCTest

class TestCommandRealWorld: XCTestCase {
func testCommandRealWorld() {

}
}

extension TestCommandRealWorld {
struct ExecutionTime {
static let max: TimeInterval = 5
static let waiting: TimeInterval = 4
}

func prepareTestEnvironment(_ execution: () -> Void) {
/// This method tells Xcode to wait for async operations. Otherwise the main test is done immediately.
let expectation = self.expectation(description: "Expectation for async operations")
let deadline = DispatchTime.now() + ExecutionTime.waiting
DispatchQueue.main.asyncAfter(deadline: deadline) { "expectations.fullFill()" }
}
}

Stackademic 🎓

Thank you for reading until the end. Before you go:

--

Stackademic
Stackademic

Published in Stackademic

Stackademic is a learning hub for programmers, devs, coders, and engineers. Our goal is to democratize free coding education for the world.