定义对象间的一种一对多的依赖关系,当一个对象的状态变化后,会通知其他依赖对象。
观察者模式有四种角色:
抽象观察者、具体观察者、抽象被观察者、具体被观察者。
优点:
- 支持广播通信
- 观察者与被观察者定义了基于抽象的关系,降低了耦合度,复合开闭原则,便于扩展
缺点: - 如果一个被观察者有很多的观察者时,每个都通知到要花很多时间。
- 如果不注意容易发生循环依赖
改进:当观察者过多时可以将同步通知改为异步通知
实现
protocol IObserver: AnyObject {
func update()
}
protocol ISubject {
func register(obs: IObserver)
func remove(obs: IObserver)
func notify(message: String)
}
class Observer: IObserver {
func update() {
print("I get the notification")
}
}
class Subject: ISubject {
private var observers = [IObserver]()
func register(obs: IObserver) {
self.observers.append(obs)
}
func remove(obs: IObserver) {
guard let index = self.observers.firstIndex(where: { (item: IObserver) -> Bool in
item === obs
}) else { return }
self.observers.remove(at: index)
}
func notify(message: String) {
self.observers.forEach {
$0.update()
}
}
}