元ネタ → [https://github.com/ochococo/Design-Patterns-In-Swift#-observer)
クラス図
図の引用元:Wikipedia: Strategy パターン
概要
The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.
Observerパターンは、オブジェクト(Subject)がその状態の変更を公開できるようにするのに使用される。他のオブジェクト(Observer)は、変更があるとすぐに通知を受けるように購読する(SubjectがObserverのインスタンスを保持する)。
サンプルコード
// Observer
protocol PropertyObserver : class {
// notify()
func willChange(propertyName: String, newPropertyValue: Any?)
// notify()
func didChange(propertyName: String, oldPropertyValue: Any?)
}
// Subject
final class TestChambers {
// 集約
weak var observer: PropertyObserver?
private let testChamberNumberName = "testChamberNumber"
// notifyOserver()
var testChamberNumber: Int = 0 {
willSet(newValue) {
observer?.willChange(propertyName: testChamberNumberName, newPropertyValue: newValue)
}
didSet {
observer?.didChange(propertyName: testChamberNumberName, oldPropertyValue: oldValue)
}
}
}
// ConcreteObserver
final class Observer : PropertyObserver {
// notify()
func willChange(propertyName: String, newPropertyValue: Any?) {
if newPropertyValue as? Int == 1 {
print("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
// notify()
func didChange(propertyName: String, oldPropertyValue: Any?) {
if oldPropertyValue as? Int == 0 {
print("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
// usage //
var observerInstance = Observer()
var testChambers = TestChambers()
// addObserver()
testChambers.observer = observerInstance
testChambers.testChamberNumber += 1
クラス図との対応
| サンプルコード | クラス図 |
|---|---|
| PropertyObserver | Observer |
| willChange, didChange | notify |
| サンプルコード | クラス図 |
|---|---|
| TestChambers | Subject |
| observer | 集約(aggregate) |
| willSet, didSet | notifyOserver |
| サンプルコード | クラス図 |
|---|---|
| Observer | ConcreteObserver |
| willChange, didChange | notify |
考察
Observer = Subscriber(購読)/ Subject = Publisher(発行)
TestChambersがPropertyObserver型(Observerをアップキャスト)のインスタンスを持つ(集約)。
TestChambersはストアドプロパティにより値の状態を監視し、変化があるとPropertyObserverインスタンスのwillChange/Didchangeを呼ぶ(ポリモーフィズム)。こうしてTestChambersは値の変化があった場合、PropertyObserverインスタンスに通知する。
