One of my favorite design patterns, is the Observer Pattern. The Observer Pattern is used far more often then you might realize. The Observer Pattern is quintessential, for instance, in most GUI applications. Most applications that respond to key strokes, mouse clicks, or network updates use Observer Pattern. The idea, is that some object in the application is observable, and it has other objects that observe it.
It’s a lot like a bunch of soldiers waiting for the order to charge. The general is observable, and the soldiers are observers. When the general gives an order, the soldiers react in a way appropriate to the order. This is the essence of the Observer Pattern. Here’s the class diagram of the situation :

The difference between the Observer Pattern and other design patterns mentioned here, is that there are (at least) two classes required to implement the Observer Pattern. One class is the Observable. It binds to events in the Observable class. The second class is the Observable class. This class is the traffic cop for the entire system. This class will define where the Observer will receive notifications regarding the state of the Observable object. Here’s some basic code to make the point:
< ?php /** * Class that is the general to the soldiers */ class Observable { private $_observers = array(); /** * public function to add observers to the stack */ public function addObserver (Observer $observer) { // APPEND the provided observer to the observer stack $this->_observers[] = $observer; } // END addObserver /** * function to let the observers know to check the status of the observable object */ public function notifyObservers ( ) { // ITERATE through each of the observers in the stack ... foreach ($this->_observers as $observer) { // UPDATE the observer $observer->Update($this); } } // END notifyObservers } // END Observable /** * Class that is the soldiers to the genereal */ class Observer { /** * Implementation of the observer's update function */ public function Update (Observable $observable) { // do whatever it is that the observer should do when notified } // END Notify } // END Observer
Related posts:
- Decorator Pattern In our ongoing series about design patterns, we introduce the...
- Factory Pattern In following the theme of design patterns we’re starting this...
- Singleton Pattern One of the things I see all the time with...
Tags: code, design pattern, Development, ood, oop, PHP