Skip to content

Instantly share code, notes, and snippets.

@HassanAli9
Created July 14, 2023 22:47
Show Gist options
  • Save HassanAli9/b618a1c37fa6818df0ac882cc922f45c to your computer and use it in GitHub Desktop.
Save HassanAli9/b618a1c37fa6818df0ac882cc922f45c to your computer and use it in GitHub Desktop.
import UIKit
//MARK: - This example before implementing command pattern
//
class Light {
func turnOn() {
print("Light is on")
}
func turnOff() {
print("Light is off")
}
}
class Switch {
func press(on: Bool) {
let light = Light()
if on {
light.turnOn()
} else {
light.turnOff()
}
}
}
let lightSwitch = Switch()
lightSwitch.press(on: true) // Light is on
lightSwitch.press(on: false) // Light is off
//MARK: - This example aftre implementing command pattern
//
protocol Command {
func execute()
}
class Light {
func turnOn() {
print("Light is on")
}
func turnOff() {
print("Light is off")
}
}
class Switch {
var command: Command?
func press() {
command?.execute()
}
}
class TurnOnCommand: Command {
let light: Light
init(light: Light) {
self.light = light
}
func execute() {
light.turnOn()
}
}
class TurnOffCommand: Command {
let light: Light
init(light: Light) {
self.light = light
}
func execute() {
light.turnOff()
}
}
let light = Light()
let switchButton = Switch()
switchButton.command = TurnOnCommand(light: light)
switchButton.press() // Light is on
switchButton.command = TurnOffCommand(light: light)
switchButton.press() // Light is off
//MARK: - This example aftre implementing command pattern with undo
//
protocol Command {
func execute()
func undo()
}
//Receiver
class Light {
var isOn = false
func turnOn() {
isOn = true
print("Light is on")
}
func turnOff() {
isOn = false
print("Light is off")
}
}
//Invoker
class Switch {
var commandHistory = [Command]()
func execute(command: Command) {
command.execute()
commandHistory.append(command)
}
func undo() {
guard let command = commandHistory.popLast() else { return }
command.undo()
}
}
class TurnOnCommand: Command {
let light: Light
init(light: Light) {
self.light = light
}
func execute() {
light.turnOn()
}
func undo() {
light.turnOff()
}
}
class TurnOffCommand: Command {
let light: Light
init(light: Light) {
self.light = light
}
func execute() {
light.turnOff()
}
func undo() {
light.turnOn()
}
}
let light = Light()
let switchButton = Switch()
let turnOnCommand = TurnOnCommand(light: light)
switchButton.execute(command: turnOnCommand) // Light is on
let turnOffCommand = TurnOffCommand(light: light)
switchButton.execute(command: turnOffCommand) // Light is off
switchButton.undo() // Light is on
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment