-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathStrategyPattern.md
62 lines (46 loc) · 1.22 KB
/
StrategyPattern.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
# 策略模式
定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
## 样例

```swift
protocol Strategy {
func operation(a: Int, b: Int) -> Int
}
class OperationAdd: Strategy {
func operation(a: Int, b: Int) -> Int {
a + b
}
}
class OperationSubstract: Strategy {
func operation(a: Int, b: Int) -> Int {
a - b
}
}
class OperationMultiply: Strategy {
func operation(a: Int, b: Int) -> Int {
a * b
}
}
class Context {
private var strategy: Strategy
init(strategy: Strategy) {
self.strategy = strategy
}
func executeStrategy(a: Int, b:Int) {
strategy.operation(a: a, b: b)
}
}
var context = Context(strategy: OperationAdd())
print("10 + 5 = \(context.executeStrategy(a: 10, b: 5))")
context = Context(strategy: OperationSubstract())
print("10 - 5 = \(context.executeStrategy(a: 10, b: 5))")
context = Context(strategy: OperationMultiply())
print("10 * 5 = \(context.executeStrategy(a: 10, b: 5))")
```
结果显示:
```sh
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
```