-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathStatePattern.md
More file actions
84 lines (64 loc) · 1.63 KB
/
StatePattern.md
File metadata and controls
84 lines (64 loc) · 1.63 KB
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
# 状态模式
允许对象在内部状态发生改变时改变它的行为,对象看起来好像修改了它的类。
## 样例

```swift
class Context : CustomDebugStringConvertible {
private var state: State = UnauthorizedState()
var isAuthorized: Bool {
get {
return state.isAuthorized(context: self)
}
}
var userId: String? {
get {
return state.userId(context: self)
}
}
func changeStateToAuthorized(userId: String) {
state = AuthorizedState(userId: userId)
}
func changeStateToUnauthorized() {
state = UnauthorizedState()
}
var debugDescription: String {
return "isAuthorized: \(isAuthorized), userId:\(userId ?? "")"
}
}
protocol State {
func isAuthorized(context: Context) -> Bool
func userId(context: Context) -> String?
}
class UnauthorizedState: State {
func isAuthorized(context: Context) -> Bool {
false
}
func userId(context: Context) -> String? {
nil
}
}
class AuthorizedState: State {
let userId: String
init(userId: String) {
self.userId = userId
}
func isAuthorized(context: Context) -> Bool {
true
}
func userId(context: Context) -> String? {
userId
}
}
let userContext = Context()
print(userContext)
userContext.changeStateToAuthorized(userId: "oldbird")
print(userContext)
userContext.changeStateToUnauthorized()
print(userContext)
```
结果显示:
```swift
isAuthorized: false, userId:
isAuthorized: true, userId:oldbird
isAuthorized: false, userId:
```