+3

A good example of observer design pattern

Can anyone share a code reference to describe good use case of observer design pattern ? I am into c++

3/2/2020 7:32:03 PM

Ketan Lalcheta

3 Answers

New Answer

+4

Don't have an immediate code reference. But a common use case is editing of data on one window update the contents of other windows to reflect the latest upto date status like in stock market. Other windows register themselves with the main window as observers. In turn when the contents of the main window changes it sends notification to all the registered windows which then fetch the updated data to update their contents.

+4

Not a C++ example but if you have seen web code even once in your life, you will probably know window.addEventListener('click', function () { ... }); And so every time the user clicks something, a message is sent to every observer that is willing to listen! What's great is that the Observer doesn't need to do much, it just calls .listen on the Observable. And the Observable doesn't need to do much either, it just walks through an array of Observables and calls them. It's an easy way to make anything talk to anything.

+3

Event listeners use the observer pattern, usually used with UI, among other stuff, pretty much as ~swim~ described. Sadly I can't find any good examples right off the bat. :(