-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathCommandPattern.md
119 lines (88 loc) · 2.63 KB
/
CommandPattern.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
# 命令模式
将一个请求封装成一个对象,从而使您可以用不同的请求对客户进行参数化。
在软件系统中,行为请求者与行为实现者通常是一种紧耦合的关系,但某些场合,比如需要对行为进行记录、撤销或重做、事务等处理时,这种无法抵御变化的紧耦合的设计就不太合适。
## 样例

```swift
protocol Command {
func execute()
func undo()
}
class Content : CustomDebugStringConvertible{
var msg: String
init(_ msg: String) {
self.msg = msg
}
var debugDescription: String {
return msg
}
}
extension String {
subscript(_ indexs: Range<Int>) -> String {
let beginIndex = index(startIndex, offsetBy: indexs.lowerBound)
let endIndex = index(startIndex, offsetBy: indexs.upperBound)
return String(self[beginIndex..<endIndex])
}
}
class CopyCommand: Command {
private var content: Content
init(content: Content) {
self.content = content
}
func execute() {
content.msg += content.msg
}
func undo() {
content.msg = content.msg[0..<content.msg.count/2]
}
}
class DeleteCommand: Command {
private var content: Content
private var deleted: String?
init(content: Content) {
self.content = content
}
func execute() {
deleted = content.msg[0..<5]
content.msg = content.msg[5..<content.msg.count]
}
func undo() {
if let del = deleted {
content.msg = del + content.msg
}
}
}
class InsertCommand: Command {
private var content: Content
private var ins: String = "https://oldbird.run"
init(content: Content) {
self.content = content
}
func execute() {
content.msg += ins
}
func undo() {
content.msg = content.msg[0..<content.msg.count - ins.count]
}
}
let content = Content("hello oldbirds.")
print("原始数据:\(content)")
let insertCommand: Command = InsertCommand(content: content)
insertCommand.execute()
insertCommand.undo()
let copyCommand: Command = CopyCommand(content: content)
copyCommand.execute()
copyCommand.undo()
let deletedCommand: Command = DeleteCommand(content: content)
deletedCommand.execute()
deletedCommand.undo()
let commands: [Command] = [InsertCommand(content: content), CopyCommand(content: content), DeleteCommand(content: content)]
commands.forEach { $0.execute()}
commands.reversed().forEach { $0.undo() }
print("最终数据:\(content)")
```
结果显示:
```sh
原始数据:hello oldbirds.
最终数据:hello oldbirds.
```