Chapter 8: Observer Pattern
大綱
When should you use it?
The observer pattern lets one object observe changes on another object.
The subject is the object that’s being observed.
The observer is the object doing the observing.

When should you use it?
Use the observer pattern whenever you want to receive changes made on another object.
This pattern is often used with MVC, where the view controller is the observer and the model is the subject.
Playground example
目標:透過兩種不同方式建立observer pattern
Using key value observation (KVO)
Using an Observable wrapper
Using key value observation (KVO)
Using an Observable wrapper
Observable wrapper實作
What should you be careful about?
Before you implement the observer pattern, define what you expect to change and under which conditions.
If you can’t identify a reason for an object or property to change, you’re likely better off not implementing KVO/Observable immediately for it.
Tutorial project
Key points
The observer pattern lets one object observe changes on another object. It involves two types: the subject and observer.
The subject is the object that’s being observed, and the observer is doing the observing.
One way to implement the observer pattern is using KVO. However, this requires you to subclass NSObject, which isn't always desirable.
Another way to implement the observer pattern is using an Observable wrapper class. This isn’t provided by Swift, so you must write your own. However, it doesn’t require you to depend on NSObject, Foundation or any other frameworks.
Last updated