Define a Subscription Mechanism in order to Notify Multiple Objects
Swift ā Problems Catalogue #13
Problem Definition:
Consider the following scenario. You have to implement a bird watching app š¦¤ how lovely. This app needs to scan birds when they appear (the key word is when) and notify subscribed enthusiasts.
In a nutshell we need an event based system that can transmit information from one entity to multiple entities at the same time.
Problem Solution:
Solution āObserver itās a behavioral design pattern that allows you to create a subscription mechanism in order to notify multiple objects at the same time.
Real-World Usage:
First, as always, we start with a protocol āØ that has a notify method. With this method the entity that receives information will receive the notification and do something with it.
Next, letās create two types of enthusiasts, a duck one š¦ and a stork oneš¦© (yup, thatās a flamingo emoji) and conform them to the Observer protocol. Implementing the notify(scanner: BirdScanner) we can verify the notificationās observedBird state and based on it we can do some business logic.
Now, letās handle the entity that āsendsā information. Technically it sends itself.
The BirdScanner has an array of observers and if the notify() method is called it goes through them and calls every observerās notify method and passes itself and exposing the observedBird variable.
When talking about the observer design pattern, the BirdScanner class is called usually a Subject.
Also, we need two additional important methods, the subscribe and the unsubscribe method that adds and removes observers from our array.
Finally, letās put everything together in our BirdWatchingApp and use our subscription mechanism to itās fullest.
From this point on, the sky is the limit š wellā¦almost.
Of course, this design pattern has its limitations but used in moderation, itās a great tool in our development toolbox.
This is the next article in the Swift Problems Catalogue series in which Iāll tackle general software development problems. The aim is to have a quick reference guide that can be easily accessed when having a design/algorithm dillemma.
Let me know what you think and donāt be shy to share where and when this pattern simplified your coding experience š¶