-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathTemplatePattern.md
73 lines (53 loc) · 1.27 KB
/
TemplatePattern.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
# 模板模式
定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
## 样例

```swift
protocol Game {
func initialize()
func start()
func end()
}
extension Game {
func play() {
initialize()
start()
end()
}
}
final class Cricket: Game {
func initialize() {
print("Cricket Game Initialized! Start playing.")
}
func end() {
print("Cricket Game Finished!")
}
func start() {
print("Cricket Game Started. Enjoy the game!")
}
}
final class Football: Game {
func initialize() {
print("Football Game Initialized! Start playing.")
}
func end() {
print("Football Game Finished!")
}
func start() {
print("Football Game Started. Enjoy the game!")
}
}
var game: Game = Cricket()
game.play()
game = Football()
game.play()
```
结果显示:
```swift
Cricket Game Initialized! Start playing.
Cricket Game Started. Enjoy the game!
Cricket Game Finished!
Football Game Initialized! Start playing.
Football Game Started. Enjoy the game!
Football Game Finished!
```