命令模式

命令模式(Command Pattern)

命令模式是一种行为模式,将执行操作的信息封装到命令对象中。它包含以下3个类型:

  1. invoker:储存和执行命令
  2. command:将行为封装成对象
  3. receiver:command所作用的对象

使用举例

1.创建Receiver

1
2
3
4
// MARK: - Receiver
public class Door {
public var isOpen = false
}

2.创建Command

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class DoorCommand {
public let door: Door
public init(_ door: Door) {
self.door = door
}
public func execute() { }
}
public class OpenCommand: DoorCommand {
public override func execute() {
print("opening the door...")
door.isOpen = true
}
}
public class CloseCommand: DoorCommand {
public override func execute() {
print("closing the door...")
door.isOpen = false
}
}

3.创建invoker

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// MARK: - Invoker
public class Doorman {
public let commands: [DoorCommand]
public let door: Door
public init(door: Door) {
let commandCount = arc4random_uniform(10) + 1
self.commands = (0 ..< commandCount).map { index in
return index % 2 == 0 ?
OpenCommand(door) : CloseCommand(door)
}
self.door = door
}
public func execute() {
print("Doorman is...")
commands.forEach { $0.execute() }
}
}

4.使用命令模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// MARK: - Example
public let isOpen = true
print("You predict the door will be " +
"\(isOpen ? "open" : "closed").")
print("")
let door = Door()
let doorman = Doorman(door: door)
doorman.execute()
print("")
if door.isOpen == isOpen {
print("You were right! :]")
} else {
print("You were wrong :[")
}
print("The door is \(door.isOpen ? "open" : "closed").")

其他例子

  1. 改变一个视图的明亮程度:http://jackliu17.github.io/2016/06/03/iOS%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F-%E5%91%BD%E4%BB%A4/
  2. 与普通写法的比较:https://yq.aliyun.com/articles/37261
  3. 撤销操作:https://juejin.im/post/5844c329ac502e006ba97570
  4. 屏幕变量和撤销:https://www.jianshu.com/p/c62e1bc04bf1