Design Patterns Reference: Observer

The Observer Design Pattern facilitates the creation of objects that watch the state of a target object and provides state targeted functionality that is uncoupled from the core object.

The most obvious example, applications that support some type of plugin system. Another example, cache systems, or message notification (example, members are notified when an item is in stock, to add that members may also be notified when it’s out of stock, simply add another observer, or perhaps another that texts them rather than emailing them…and so on).

When adding features to software that are activated by an action or state change but are loosely coupled, objects based on the Observer Design Pattern should be created.

MyObject is the Observable object. It contains a protected array of observers. A public method addObserver() takes an instance of an observer and stores it in the array.

A public method doSomething() applies a state change to MyObject, whose notify() public method then loops through the array of observers.

Each such MyObjectObserver has a public method change(), that accepts an instance of MyObject, which modifies said object via a notify() method of MyObject that calls MyObjectObserver’s change() method directly as it’s encountered in the array of observers.