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: inReviewapproved, 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:

class App {
	    enum ModerationState {
	        case submittedForReview
	        case inReview
	        case approved
	        case rejected
	    }

	    var moderationState: ModerationState = .submittedForReview
	}

Next, let’s create a Command.

Command

We start with a base class that each specific command with inherit from:

class ModerationCommand {
	    var app: App
	    init(app: App) {
	        self.app = app
	    }

	    public func execute() {}
	}

The command depends on the single App object that we will mutate accordingly in subclasses. Now let’s create these subclasses:

class StartReviewCommand: ModerationCommand {
	    override func execute() {
	        app.moderationState = .inReview
	        print("The app is in review")
	    }
	}

	class RejectCommand: ModerationCommand {
	    override func execute() {
	        app.moderationState = .rejected
	        print("The app was rejected")
	    }
	}

	class ApproveCommand: ModerationCommand {
	    override func execute() {
	        app.moderationState = .approved
	        print("The app was approved")
	    }
	}

As we can see, each command changes the moderationState property of the App object inside the execute() method.

With commands done, now we need to create an Invoker.

#ios #xcode #mobile #programming #swift #command

Implement the Command Design Pattern in Swift 5
2.70 GEEK