任何高階語言都離不開幾個高頻設計模式。在 iOS 開發中與我們最常打交道的,莫過於單例、觀察者與工廠這三個。本文就把觀察者模式講清楚。
觀察者模式的本質是一種發布—訂閱模型,用來消除行為各異的物件之間的耦合。透過它,不同物件可以協同工作,也能被複用到別處。Observer 向 Subject 訂閱通知,ConcreteObserver 實作 Observer 並覆寫其 update 方法;一旦 Subject 需要通知任何變更,它就向內部註冊的 Observer 發送 update 訊息,ConcreteObserver 在 update 的實作中取得 Subject 的內部狀態並做後續處理。

換句話說,觀察者模式定義了一種一對多的依賴關係:當一個物件的狀態改變,所有依賴它的物件都會收到通知並自動更新。

用 N 個 Observer 去擴充 Subject 的行為,每個 Observer 各自持有處理 Subject 資訊的特定實作,耦合就這樣被消掉了。
在 Cocoa Touch 中,KVO 與通知中心其實都是觀察者模式的實作,所以接下來就聚焦這兩個。
NSNotificationCenter 與 NSNotification 構成一對多模型,讓彼此不認識的物件也能通訊。
發送通知:
NSNotification *subjectMessage = [NSNotification notificationWithName:@"subjectMessage" object:self]; NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter]; [notificationCenter postNotification:subjectMessage];
向 NSNotificationCenter 發送 defaultCenter 可取得實例引用。每個進程只有一個預設通知中心,因此它是單例。
註冊觀察:
NSNotificationCenter *notificationCenter1 = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver:self
selector:@selector(update:)
name:@"subjectMessage"
object:nil];
實作回呼:
- (void)update:(NSNotification *)notification {
if ([[notification name] isEqualToString:@"subjectMessage"]) {
NSLog(@"%@", @"猴子派來的救兵去哪了?");
}
}
別忘了註銷:
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
抽象主題協議:
#import <Foundation/Foundation.h> @class Observer; @protocol Subject <NSObject> @required // 增加觀察者 - (void)attach:(Observer *)observer; // 移除觀察者 - (void)detach:(Observer *)observer; // 為觀察者發送通知 - (void)notifyObservers; @end
觀察者協議:
#import <Foundation/Foundation.h> @protocol Observer <NSObject> @required - (void)update; @end
具體觀察者:
#import <Foundation/Foundation.h> #import "Observer.h" @interface ConcreteObserver : NSObject <Observer> @end
具體主題:
#import <Foundation/Foundation.h>
#import "Subject.h"
@interface ConcreteSubject : NSObject <Subject>
{
NSMutableArray *observers;
}
@property (nonatomic, strong) NSMutableArray *observers;
// 單例方式取得自身
+ (ConcreteSubject *)shareConcreteSubject;
@end
KVO 是 Cocoa 提供的鍵值觀察機制,物件可以藉此取得其他物件特定屬性的變更通知。它基於 NSKeyValueObserving 非正式協議,Cocoa 透過它為遵循協議的物件提供自動化的屬性監聽能力。
通知與 KVO 都能實現觀察者模式,但側重點不同:通知由一個中心物件統一發布,關心的是廣義上的程式事件;KVO則是被觀察物件直接通知觀察者,綁定的是特定屬性的值。
先準備一個模型:
@property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *title; @property (nonatomic, assign) NSUInteger age;
初始化並賦值:
self.hero = [[Hero alloc] init]; self.hero.name = @"趙雲"; self.hero.title = @"將軍"; self.hero.age = 87;
註冊觀察 name 的變化,並要求同時回傳新舊值:
[self.hero addObserver:self
forKeyPath:@"name"
options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld
context:nil];
觸發變更:
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
self.hero.name = @"張飛";
}
在回呼中處理:
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context {
if ([keyPath isEqualToString:@"name"]) {
NSLog(@"賦值後--%@", self.hero.name);
NSLog(@"新的值--%@", change[@"new"]);
NSLog(@"以前的值--%@", change[@"old"]);
}
}
回呼輸出:

最後記得在 dealloc 中移除觀察,否則會出現懸空指針式的崩潰:
- (void)dealloc {
[self.hero removeObserver:self forKeyPath:@"name"];
}
以上是 KVO 與通知最基礎的用法。後續值得繼續挖掘的方向還很多:例如把 iOS 的 delegate、Block 放在一起對比,梳理出完整的訊息傳遞機制;或者看看 Swift 中 didSet / willSet 這種語言層級的屬性監聽,與 KVO 的 runtime 實作有什麼異同。這些都是很值得玩味的題目。