Command Design Pattern in Swift

Kelvin Tan
Swiftly Engineered iOS
3 min readNov 3, 2023

--

Photo by hannah joshua on Unsplash

Behavioral design patterns are a set of design patterns that focus on the communication and interaction between objects. The Command pattern is one of the most commonly used behavioral patterns in software development. The Command pattern is a design pattern that encapsulates a request or command as an object, allowing it to be stored, passed as a parameter, and executed at a later time. In this article, we will discuss the Command pattern and provide a Swift code example.

The Command pattern consists of four main components:

  1. Command: The Command is an interface that defines the operations that can be performed on the receiver.
  2. Concrete Command: The Concrete Command implements the Command interface and defines the binding between the action and the receiver.
  3. Receiver: The Receiver is the object that performs the action.
  4. Invoker: The Invoker is the object that requests the action from the receiver through the Concrete Command.

Now let’s look at a Swift code example that demonstrates the Command pattern in action:

// Command
protocol Command {
func execute()
}

// Concrete Command
class LightOnCommand: Command {
private let light: Light

init(_ light: Light) {
self.light = light
}

func execute() {…

--

--

Kelvin Tan
Swiftly Engineered iOS

Father, husband, software engineer. Building software and building a family, one line of code and one moment at a time. 🚀💻💙 http://ko-fi.com/kelvintanzy