-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathContents.swift
62 lines (49 loc) · 1.16 KB
/
Contents.swift
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
//: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 游戏角色
struct GameRole {
var vit: Int
var atk: Int
var def: Int
init() {
vit = 100
atk = 100
def = 100
}
func stateDisplay() {
print("生命值:\(vit)")
print("攻击力:\(atk)")
print("防御力:\(def)")
}
func saveState() -> RoleStateMemento {
return RoleStateMemento(vit: vit, atk: atk, def: def)
}
mutating func recoverState(_ memento: RoleStateMemento) {
vit = memento.vit
atk = memento.atk
def = memento.def
}
mutating func fight() {
vit = 0
atk = 0
def = 0
}
}
// 游戏状态备忘
struct RoleStateMemento {
var vit: Int
var atk: Int
var def: Int
}
// 游戏状态管理
struct RoleStateCaretaker {
var memento: RoleStateMemento
}
var p = GameRole()
p.stateDisplay()
let stateAdmin = RoleStateCaretaker(memento: p.saveState())
p.fight()
p.stateDisplay()
p.recoverState(stateAdmin.memento)
p.stateDisplay()