观察者模式的替代方案
与代理和 Combine 发布者进行比较。
观察者模式的替代方案 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 4 节课。
观察者模式的替代方案
NotificationCenter 是响应事件的一种方式。Swift 还提供了其他方案:委托、组合框架和异步流。每种方案都适合不同形式的通信。
观察者模式
观察者模式允许对象订阅来自主题的事件。NotificationCenter 是该模式的一种全局、松耦合实现。
import Foundation
// Subject posts, observers react, neither holds the other.
NotificationCenter.default.post(name: Notification.Name("tick"), object: nil)
print("Broadcast an event")委托
delegate是一种一对一连接:对象通过协议将特定事件转发给单个 delegate。这种方式明确且类型安全。
protocol DownloadDelegate: AnyObject {
func didFinish(_ bytes: Int)
}
class Downloader {
weak var delegate: DownloadDelegate?
func finish() { delegate?.didFinish(1024) }
}
print("Delegate is one-to-one and typed")委托与通知
当恰好只有一个对象关注某件事且关系明确时,请使用 delegate。当许多未知的观察者可能需要响应时,请使用 NotificationCenter。
import Foundation
// One listener -> delegate. Many/unknown listeners -> NotificationCenter.
print("Cardinality guides the choice")组合框架发布者
组合框架将事件建模为 publisher,您可以使用sink订阅它们,并使用map和filter等转换运算符。
import Combine
let subject = PassthroughSubject<Int, Never>()
let c = subject.sink { print("Got \($0)") }
subject.send(5)
_ = cNotificationCenter 发布者
组合框架可以连接 NotificationCenter:publisher(for:)会将通知转换为可供转换的数据流。
import Foundation
import Combine
let name = Notification.Name("ping")
let c = NotificationCenter.default.publisher(for: name)
.sink { _ in print("Combine got notification") }
NotificationCenter.default.post(name: name, object: nil)
_ = c组合框架运算符
组合框架擅长组合事件流程:以声明式方式进行筛选、防抖、组合和映射。
import Combine
let subject = PassthroughSubject<Int, Never>()
let c = subject
.filter { $0 > 0 }
.map { $0 * 2 }
.sink { print($0) }
subject.send(-1)
subject.send(3)
_ = c异步序列
现代 Swift 提供了AsyncStream和通知异步序列,让您可以在结构化并发中使用for await消费事件。
import Foundation
func listen() async {
let name = Notification.Name("ping")
for await _ in NotificationCenter.default.notifications(named: name) {
print("Async observed")
break
}
}
print("Can await notifications")闭包与回调
对于单个局部回调,存储一个闭包是最简单的方式,完全不需要观察者机制。
struct Button {
var onTap: () -> Void
func tap() { onTap() }
}
Button(onTap: { print("tapped") }).tap()选择方案
delegate:一对一、明确。NotificationCenter:多对多、解耦。组合框架或异步方案:适合需要转换的数据流。闭包:简单的局部回调。
import Foundation
// Match the tool to the communication shape.
print("Delegate, Notification, Combine, async, closure")权衡
NotificationCenter 灵活,但没有类型约束,也容易产生泄漏。委托和组合框架具有类型安全性;组合框架和异步方案功能更强,但代价是需要理解更多概念。
import Foundation
// Prefer typed approaches when the relationship is known.
print("Type safety vs flexibility tradeoff")快速检查
哪种机制最适合清晰的一对一类型安全关系?
回顾
观察者模式在 Swift 中有多种形式:NotificationCenter适合解耦的多对多事件,委托适合类型安全的一对一连接,组合框架和异步序列适合可组合的数据流,闭包则适合简单的回调。请根据通信形式和类型安全需求进行选择。本课程到此结束。
常见问题解答
「观察者模式的替代方案」课时是免费的吗?
是的 — 「观察者模式的替代方案」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 4 节课。
「观察者模式的替代方案」这节课中我会学到什么?
与代理和 Combine 发布者进行比较。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「观察者模式的替代方案」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 发布和观察通知
- 通知的 userInfo 载荷
- 安全移除观察者
- 观察者模式的替代方案