나중에 실행시킬 이벤트를 캡슐화시킨 객체를 만드는 행위 디자인 패턴
command.execute()
참고 자료_ MVVM
MVVM 패턴은 Command 패턴과 Data Binding 두 가지 패턴을 사용하여 구현되었습니다.
Command 패턴과 Data Binding을 이용하여 View와 View Model 사이의 의존성을 없앴습니다.
protocol Command {//command
func execute()
}
class Home {
func lockDoor() {
print("lock the door")
}
func unlockDoor() {
print("unlock the door")
}
func openGarage() {
print("open the garage")
}
func closeGarage() {
print("close the garage")
}
}
class LockDoorCommand: Command {//concrete command
private let home: Home
init(home: Home) {
self.home = home
}
func execute() {
home.lockDoor()
}
}
class UnLockDoorCommand: Command {
private let home: Home
init(home: Home) {
self.home = home
}
func execute() {
home.unlockDoor()
}
}
class OpenGarageCommand: Command {
private let home: Home
init(home: Home) {
self.home = home
}
func execute() {
home.openGarage()
}
}
class CloseGarageCommand: Command {
private let home: Home
init(home: Home) {
self.home = home
}
func execute() {
home.closeGarage()
}
}
class HomeManager { //Invoker
private let lockDoorCommand: Command
private let unlockDoorCommand: Command
private let openGarageCommand: Command
private let closeGarageCommand: Command
init(home: Home) {
lockDoorCommand = LockDoorCommand(home: home)
unlockDoorCommand = UnLockDoorCommand(home: home)
openGarageCommand = OpenGarageCommand(home: home)
closeGarageCommand = CloseGarageCommand(home: home)
}
func secure() {
lockDoorCommand.execute()
closeGarageCommand.execute()
}
func open() {
unlockDoorCommand.execute()
openGarageCommand.execute()
}
}
let manager = HomeManager(home: Home())
manager.open()
manager.secure()
/*
unlock the door
open the garage
lock the door
close the garage
*/
// 실행 기능 추상화 -> 여러 기능 수행하도록 캡슐화
protocol Command {
func execute()
}
class Button {
private var command: Command
init(command: Command) {
self.command = command
}
func setCommand(command: Command) {
self.command = command
}
func pressed() {
self.command.execute()
}
}
class Lamp {
func turnOn() {
print("Lamp On")
}
}
class LampOnCommand: Command {
private var lamp: Lamp
init(lamp: Lamp) {
self.lamp = lamp
}
func execute() {
self.lamp.turnOn()
}
}
class Alarm {
func start() {
print("Alarm Start")
}
}
class AlarmStartCommand: Command {
private var alarm: Alarm
init(alarm: Alarm) {
self.alarm = alarm
}
func execute() {
self.alarm.start()
}
}
//client
let lampOnCommand = LampOnCommand(lamp: Lamp())
let alarmStartCommand = AlarmStartCommand(alarm: Alarm())
// 램프를 켜는 버튼
let button1 = Button(command: lampOnCommand)
button1.pressed() // Lamp On
// 한 번 누르면 알람이 켜지고 두 번 누르면 램프가 켜지는 버튼
let button2 = Button(command: alarmStartCommand)
button2.pressed() // Alarm Start
button2.setCommand(command: lampOnCommand)
button2.pressed() // Lamp On