GoF의 디자인 패턴, 명령 패턴에 대해 알아본다.
해당 글은, 다음의 코드를 기반으로 이해하는 것이 편리합니다.
//
// Command.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal protocol Command {
func run()
// func undo() 필요하다면 구현하면 됨
}
//
// EnterCommand.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal class EnterCommand: Command {
internal func run() {
(0...4).forEach { _ in print() }
}
}
//
// PrintCommand.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal class PrintCommand: Command {
internal init(content: String) {
self.content = content
}
internal func run() {
print(self.content)
}
private let content: String
}
//
// TabCommand.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal class TabCommand: Command {
internal init(times: Int) {
self.times = times
}
internal func run() {
(0..<self.times).forEach { _ in print(" ", terminator: "") }
}
private let times: Int
}
//
// DecorationCommand.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal class DecorationCommand: Command {
internal func run() {
print("======================================")
}
}
//
// CommandGroup.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal class CommandGroup: Command {
internal func add(command: Command) {
self.commands.append(command)
}
internal func run() {
self.commands.forEach { $0.run() }
}
private var commands = [Command]()
}
//
// main.swift
// Command
//
// Created by Choiwansik on 2023/01/16.
//
import Foundation
internal func main() {
// 하나씩 테스트 해보기
let enterCommand: Command = EnterCommand()
enterCommand.run()
let tabCommand: Command = TabCommand(times: 3)
tabCommand.run()
let printCommand: Command = PrintCommand(content: "출력해주세요.")
printCommand.run()
let decorationCommand: Command = DecorationCommand()
decorationCommand.run()
// 기존에 만들었던 객체를 재사용해보기 (print)
let tabCommand2: Command = TabCommand(times: 6)
tabCommand2.run()
printCommand.run()
// Command Group을 통해 Batch로 만들기
let commandGroup = CommandGroup()
commandGroup.add(command: enterCommand)
commandGroup.add(command: tabCommand)
commandGroup.add(command: printCommand)
commandGroup.add(command: decorationCommand)
commandGroup.run()
}
main()
load()
, store()
와 같은 연산을 지원하면 저장소에 저장했다가 불러오는 것도 가능해진다.IBAction
으로 특정 동작 자체를 넘겨 바인딩하는 방식이 명령 패턴일 듯 하다.