Swift 5.2 Observer Pattern 观察者模式

image.png

Subscriber 观察者
Publisher 发布者
Value 被观察的对象的取值
在Swift 5.1中,可以利用@Published 轻松实现观察者模式

假设老王是Subscriber,他的儿子小明的考试成绩是Value,小明的老师是Publisher。
老王想实时观察小明的考试成绩,他就拜托老师,跟老师说“每次有新的考试成绩的时候,就发消息我,我要看看小明有没有好好学习”

上面的场景,就生成了如下代码

import  Combine
public class Student {
    
    @Published var score: Int = 0
    public init(score: Int) {
        self.score = score
    }
}

let xiaoMing = Student(score: 0)
let teacher = xiaoMing.$score
var laoWang: AnyCancellable? = teacher.sink { (score) in
    if score > 80 {
        print("Cake")
    } else {
        print("Why")
    }
}

xiaoMing.score = 50
xiaoMing.score = 90
laoWang = nil
xiaoMing.score = 95


输出结果就是

Why
Why
Cake

生成xiaoMing实例对象的时候,score赋值0,打印第一个Why,
当给score赋值50的时候,打印第二个Why,
当给score赋值90的时候,打印第一个Cake。
此时laoWang觉得小明的成绩上来了,就不想再观察了,laoWang值变为nil,
当score变为95的时候,由于观察者laoWang已经不再观察,以后的成绩变化,就不会再知道了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。