When to notify

The final thing to consider when using the Observer pattern is when to notify the Observers. The first option is to notify the Observers after any data has changed. In the above example, the Player called Notify within the AdjustHealth method. This means that the Observers will have the most up to date information immediately. However, if the AdjustHealth method is called many times in one frame, time is wasted updating the Observers many times. This problem becomes worse if the Observers were observing more than just the Player's health.

The other option would be to notify the Observers after all data has changed. This solution is obviously more efficient but a lot depends on how your system works. In the preceding example, it could be possible to update all the Player information (in this case, just the health) first, then call Notify before displaying anything.

In a game engine with many different Subjects and Observers that interact in different ways every frame, it can be difficult to know when all data has been updated. There might not be a way to sort the game objects such that all Subjects are updated before the Observers. It is possible that a HUD object that is an Observer has already been updated before the Subject gets updated. This becomes even more difficult since other systems such as physics can affect the data inside game objects.

In the end, there isn't a correct time to notify the Observers. It can be more efficient to only notify them once. However, if the system is complex, it probably isn't worth the programming trouble trying to batch all Notify calls together.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.116.118.229