Skip to content

Instantly share code, notes, and snippets.

@eofster
Last active February 1, 2016 17:20
Show Gist options
  • Save eofster/b23749ec8133d50b2464 to your computer and use it in GitHub Desktop.
Save eofster/b23749ec8133d50b2464 to your computer and use it in GitHub Desktop.
An example of using the observer pattern instead of NSnotifications and KVO
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 UserAgentEventLogger: UserAgentObserver {
func userAgentDidFinishStarting(userAgent: UserAgent) {
print("User agent started")
}
func userAgentDidFinishStopping(userAgent: UserAgent) {
print("User agent stopped")
}
}
let userAgent = UserAgent(observer: UserAgentEventLogger())
userAgent.start()
userAgent.stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment