Observer Pattern
Observer Pattern: When objects have a one to many relationship, i.e. many objects need to be updated when one object changes, and the number of these objects is not known ahead of time, this pattern can be used to implement it.
We begin by implementing 2 interfaces:
The actual observer and observable classes would implement these interfaces.
Two examples of where you might be using this:
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).
Labels: patterns
1 Comments:
At February 21, 2009 11:05 AM ,
Andrej said...
I've found a detailed info with some example on http://www.a-scripts.com/object-oriented-php/2009/02/21/the-observer-pattern/
Post a Comment
<< Home