Skip to content

Instantly share code, notes, and snippets.

@eofster
Last active November 8, 2015 14:42
Show Gist options
  • Save eofster/e5ae2141e465966f48d4 to your computer and use it in GitHub Desktop.
Save eofster/e5ae2141e465966f48d4 to your computer and use it in GitHub Desktop.
An example of using a composite observer
class UserAgent {
let observer: UserAgentObserver
init(observer: UserAgentObserver) {
self.observer = observer
}
func start() {
observer.userAgentDidFinishStarting(self)
}
func stop() {
observer.userAgentDidFinishStopping(self)
}
}
protocol UserAgentObserver {
func userAgentDidFinishStarting(userAgent: UserAgent)
func userAgentDidFinishStopping(userAgent: UserAgent)
}
class CompositeUserAgentObserver {
let observers: [UserAgentObserver]
init(observers: [UserAgentObserver]) {
self.observers = observers
}
}
extension CompositeUserAgentObserver: UserAgentObserver {
func userAgentDidFinishStarting(userAgent: UserAgent) {
onEachObserver { $0.userAgentDidFinishStarting(userAgent) }
}
func userAgentDidFinishStopping(userAgent: UserAgent) {
onEachObserver { $0.userAgentDidFinishStopping(userAgent) }
}
private func onEachObserver(function: UserAgentObserver -> Void) {
for observer in observers { function(observer) }
}
}
class UserAgentEventLogger: UserAgentObserver {
func userAgentDidFinishStarting(userAgent: UserAgent) {
print("User agent started")
}
func userAgentDidFinishStopping(userAgent: UserAgent) {
print("User agent stopped")
}
}
let eventLoggers: [UserAgentObserver] = [UserAgentEventLogger(), UserAgentEventLogger()]
let compositeObserver = CompositeUserAgentObserver(observers: eventLoggers)
let userAgent = UserAgent(observer: compositeObserver)
userAgent.start()
userAgent.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment