Last active
November 8, 2015 14:42
-
-
Save eofster/e5ae2141e465966f48d4 to your computer and use it in GitHub Desktop.
An example of using a composite observer
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
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