We begin by implementing 2 interfaces:
- IObservable: This is the object that gets observed - whose change would affect other objects
- IObserver: This represents objects that are the observers
Interface IObservable {
// The attachObserver function adds the passed object to an array
public function attachObserver(obj);
// The detachObserver function removes the passed object from the array
public function detachObserver(obj);
// Notify all the objects in the array - loop through the objects and call the update method
// Note: All the elements in the array implement the IObserver interface and hence
// support the "update" method
public function notify();
// Function would be called by the Observers to get state information about the object
public function getState();
}
Interface IObserver {
// The method that performs the action that needs to be done on change of the observable
public function update();
}
The actual observer and observable classes would implement these interfaces.
Two examples of where you might be using this:
- In a web application, you may register screens with your business model objects (representing underlying data) - hence when the model gets updated, the screens get updated automatically.
- Another example may be, say you are making a game - and you when 1 object performs a task - such as a commander issuing a fire order, all units within the commanders range should fire (they would have registered with the commander object - and as they observed a change, they perform an action).
discuss this topic to forum
