-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArchitecture.cs
94 lines (70 loc) · 2.1 KB
/
Architecture.cs
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
using System;
// UI 高层 class Panel
// UI 低层 class Button
// 底层 struct Int32(int)
// 原则: 低层不能知道高层(完全不知它的class), 高层可以知道低层
public class Panel {
public int playerLevel;
public Button startGameBtn;
public void Inject(Button btn) {
startGameBtn = btn;
// 用法2
// startGameBtn.OnGetPlayerLevelHandle = () => {
// return playerLevel;
// };
startGameBtn.OnGetPlayerLevelHandle = GetPlayerLevel;
}
int GetPlayerLevel() {
return playerLevel;
}
// 低层调高层的方法之一: 访问低层字段
public void Update() {
if (startGameBtn.isClicked) {
startGameBtn.LogPlayerLevel(playerLevel);
}
}
}
public class Button {
public bool isClicked;
public Func<int/*playerLevel*/> OnGetPlayerLevelHandle;
public Button() { }
// 不要这么做
// 但它知道了高层的存在, 所以在架构中非常不好
// 因为低层依赖了高层
// public void LogPlayerLevel(Panel panel) {
// System.Console.WriteLine(panel.playerLevel);
// }
// 正确用法1
public void LogPlayerLevel(int playerLevel) {
System.Console.WriteLine(playerLevel);
}
// 正确用法2
public void LogPlayerLevel() {
int level = OnGetPlayerLevelHandle.Invoke();
System.Console.WriteLine(level);
}
public void OnClick() {
LogPlayerLevel();
}
}
public static class Architecture {
public static void Entry() {
Button btn = new Button();
Panel panel = new Panel();
panel.playerLevel = 999;
panel.Inject(btn);
// 通过委托, 从低层获取到高层的某个值
btn.OnClick();
{
Predicate<int> pred = (int i) => {
return i > 0;
};
bool isTrue1 = pred.Invoke(3);
// 用 Func 替代 Predicate
Func<int, bool> fakePred = (int i) => {
return i > 0;
};
bool isTrue2 = fakePred.Invoke(3);
}
}
}