Observer Design Pattern
“Publisher / Subscriber relationship”
The Observer pattern lets us define a subscription mechanism to notify multiple objects about any events that happen to the object that is being observed.
When to use Observer Pattern?
Want some classes to react based on changes in other classes.
Resources
- https://refactoring.guru/design-patterns/observer
- In C++: https://refactoring.guru/design-patterns/observer/cpp/example
Formally learned in CS247.
Pieces of the Observer Pattern
- Publisher: Generates some data, change in state
- Subscriber: Can dynamically subscribe or unsubscribe for various publishers. Should react when data is changed.
Steps
ConcreteSubject
has its state updatednotifyObservers
is called - either byConcreteSubject
or some controller (like themain
function)notify
is called on each observer inSubject
’s observer list- This calls
ConcreteSubject::notify
, by the assumption it is pure virtual ConcreteObserver
callsgetState
onConcreteSubject
, uses info as necessary
Example: Spreadsheet Application
- Publishers: Cells (Subjects)
- Subscribers: Charts (Observers)
When a cell changes, charts that are observing that cell must re-render, display new information.
May have different types of publishers / subscribers, e.g. - different charts require different logic for re-rendering.
Full Example: Twitter clone
Tweeters are subjects. Followers which are observers, can only follow one tweeter.
- Notice that for the above code, the
elon.tweet()
is called in themain()
loop. This is not mandatory, more like implementation detail.
Important Note
Notice that this only works because destruction happens in reverse order!
Wait, I’m slightly confused, why does it work? Why doesn’t the program leak memory here? Ahh, I think if you had something like declaring
Follower
first, then declaringTweeter
, you would get memory leak, because theTweeter
would get destroyed first. But that is not the case here,Follower
s gets destroyed first, thenTweeter
. See Destructor.
Other Variants
One should note that other variants of the Observer pattern exist. For example, passing a
Subject&
vianotify
method.