-
-
Save KrisYu/da0485977d645f2d138ff373dad294e1 to your computer and use it in GitHub Desktop.
Swift observer pattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
protocol Observer { | |
var id: String { get } | |
func update(_ string: String) | |
} | |
extension Observer { | |
func update(_ string: String) { | |
print("\(type(of: self)) に届いた新しい値は \(string) です。") | |
} | |
} | |
protocol Subject: class { | |
var observers: [Observer] { get set } | |
func add(_ observer: Observer) | |
func remove(_ observer: Observer) | |
func notify(newString: String) | |
} | |
extension Subject { | |
func add(_ observer: Observer) { | |
observers.append(observer) | |
} | |
func remove(_ observer: Observer) { | |
for (index, registerdObserver) in observers.enumerated() { | |
if registerdObserver.id == observer.id { | |
self.observers.remove(at: index) | |
} | |
} | |
} | |
func notify(newString: String){ | |
print("新しい値 \(newString) を observer に通知します。") | |
observers.forEach { observer in | |
observer.update(newString) | |
} | |
} | |
} | |
final class SubjectA: Subject { | |
var observers: [Observer] = [] | |
} | |
final class ObserverA: Observer { | |
var id = UUID().uuidString | |
} | |
final class ObserverB: Observer { | |
var id = UUID().uuidString | |
} | |
let subjectA = SubjectA() | |
let observerA = ObserverA() | |
let observerB = ObserverB() | |
subjectA.add(observerA) | |
subjectA.add(observerB) | |
subjectA.notify(newString: "New!") | |
subjectA.remove(observerB) | |
subjectA.notify(newString: "New!!!!!!!!!!!!!!!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment