The observer behavioral pattern allows you to be notified of any changes instead of constantly checking.

You’ll almost certainly have many different objects in your application that all use some common information.

If this is a financial application, then you might have some daily balances that you need to show to the user. A good application will show the balances in multiple ways maybe in a table where they can be changed and in a chart where they can be viewed graphically.

If this is an adventure game, then the hero will have a position and a direction. There will usually be a main view that shows the environment that the hero is looking at. And there might be a miniature map in the corner that shows a dot for the position and rotates to show the direction.

In each of these cases, you could make one of the views dependent on the other. The chart could constantly ask the the table if anything has changed. It would have to do this rapidly over and over. The miniature map could constantly ask the main view for the position and direction over and over. Or maybe instead you decide to have the table inform the chart whenever it changes. And the main adventure view could notify the miniature map anytime the hero moves or turns.

But what do you do when the user wants a different type of chart? Or even worse, how do you handle the case where the user zooms in on the miniature map and makes it go full screen so there’s no more main view?

The solution is to refactor the data into its own class that’s not responsible for any of the views. Then any class that is interested to know when the data changes can call a method on the data class to attach a callback method which the data class will call. This method will be called update. The data class defines what the update method looks like because it’ll be the one calling the method. The data class actually just calls however many update methods were attached one at a time until it’s called all of them.

Once this is done, each of the views become equals and are no longer dependent on each other. They are each waiting to have their update method called. The episode describes more details and gives some other design considerations you should be aware of.


What's on your mind?

On a scale of 0 to 10, how likely are you to refer us to a friend?