The observer pattern

By | March 21, 2018

The observer pattern is the most powerful pattern within software engineering when it comes to communication (event handling) within an application. It is also called publisher and subscriber pattern and also known as the dispatcher pattern. The observer is a structural and behavioral pattern.

The observer is mostly used where different sections of user interfaces need to respond to the state changes. The observer registers itself with the subject. In this pattern the subject knows about all the observers and each observer knows about the subject. When the state of an observer is altered it notifies the Subject. The subject is responsible for notifying all observers other observer that  conditions have changed in the application. Each observer is notified by the means of the update method in this example and each observer adjusts itself.

 

In the example above I added a little more detail to make it cleared, it shows how this can be used. In a paint application where the UI needs to adjust to the state of the canvas the observer pattern can be used. Each observer will instruct the Subject which is the canvas in this example once the state has changed which will then in turn update all the other observers.

 

 

Leave a Reply

Your email address will not be published.