-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathContents.swift
More file actions
60 lines (47 loc) · 1.14 KB
/
Contents.swift
File metadata and controls
60 lines (47 loc) · 1.14 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
//: Playground - noun: a place where people can play
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Design-Patterns
import UIKit
// 协议
protocol Subject {
var updates: [() -> ()] { get }
func notify()
}
class Boss: Subject {
var updates: [() -> ()] = []
func notify() {
for i in 0..<updates.count {
updates[i]()
}
}
}
// 看股票
class StockObserver {
var name: String
var sub: Subject
init(_ name: String, _ sub: Subject) {
self.name = name
self.sub = sub
}
func turnOffStockMarket() {
print("\(name) 关闭股票,继续工作")
}
}
// 看 NBA
class NBAObserver {
var name: String
var sub: Subject
init(_ name: String, _ sub: Subject) {
self.name = name
self.sub = sub
}
func turnOffNBA() {
print("\(name) 关闭 NBA,继续工作")
}
}
let boss = Boss()
let colleagueA = StockObserver("A", boss)
let colleagueB = NBAObserver("B", boss)
boss.updates.append(colleagueA.turnOffStockMarket)
boss.updates.append(colleagueB.turnOffNBA)
// 发出通知
boss.notify()