Swift Design Pattern: Observer Pattern
Listen, then act.
Today, I’m going to explain about observer pattern and implementation in Swift. So what is that?
Real world case
Imagine that you’re a firefighter who is always ready for the emergency call when there’s something aflame. If there’s a call coming from somewhere to your handy talkie, you must prepare your perks and get ready to extinguish the flame.
Definition
So, observer pattern is a design pattern which emphasized on object reaction when there’s a change or another events from Observable. From above example, handy talkie act as Observable, to give a notification to Observer (firefighter).
Characteristics
Observer has a characteristics to fulfill the pattern as follows:
- Has a observables
- Attaching & removing observables
- Notify the observables about the changes
Codes
So, this pattern contains 2 protocols, Observable
and Observer
and some of concrete class or struct which conform with Observable
or Observer
protocol.
Every observer has a method update<T>(with:)
to react with observable’s data changes.
So, this is generic Observable which their value type can be set by any types, such as String
, Bool
, Int
, or even closures.
Now, we’re going to make the class which conform the Observable
protocol, we can name it Variable
for example. Class Variable
is generic, so you can define the variable’s value
type whatever you want.
We have a private attributes, _value
and _observers
. These attributes is used to store a value and list of observers that can be retrieved or set through get/set properties.
If we set value
property, it will call notifyAllObservers<T>(with:)
to notify all observers that has been registered before.
Now, we’re going to make a class which conform Observer
protocol. This object which instantiated from this class can react with observer’s data changes when registered to Observer. We name it, MyObserver
.
There’s a update<T>(with:)
method that can be used to react with observer data changes, and retrieve a new value from observer.
Now, write this driver program as follows to test the observable and observer is working or not.
So, if we run that driver program, it will have a output like this
It works :)
What’s next?
I hope you’ll understand about how to implement observer design pattern in Swift and understand how it works, because NotificationCenter
or KVO mechanism are built on top of observer pattern. If there’s something that can’t be understood, let me know in the comment. Cheers.