Implement the Command Design Pattern in Swift 5
Encapsulate and execute actions over time
In this article, we will learn about the Command design pattern and implement it in an Xcode Playground.
In short, the Command is a behavioral design pattern that helps us encapsulate actions (commands) and execute them at a later point in time.
It involves the following components:
- Invoker — an object that executes its commands
- Command — an action that needs to be performed
- Receiver — an object that is being acted upon.
Let’s Start
Consider an example of a moderator who reviews an app. The moderation process may have different states: inReview
, approved
, and rejected
. We want to set specific commands for the moderator and execute them one-by-one with some delay. So let’s start creating the required components.
Receiver
Our receiver is an App
class that has a dependency on the ModerationState
. Its initial state is submittedForReview
: