vendredi 22 avril 2011

Design pattern observer

Définition

Le design pattern observer définit une relation un-à-plusieurs entre des objets de sorte que quand un objet change d'état, toutes ses relations sont notifiées et mises à jour automatiquement.

Diagramme UML

Diagramme de classes du design pattern observer


Exemple en PHP

Depuis PHP 5.1, la Standard PHP Library (SPL) fournit les interfaces SplSubject et SplObserver pour implémenter le design pattern observer.
class Subject implements SplSubject
{
    private $observers = array();
    private $variable;
    
    public function attach(SplObserver $observer)
    {
        $id = spl_object_hash($observer);
        $this->observers[$id] = $observer;
    }
    
    public function detach(SplObserver $observer)
    {
        $id = spl_object_hash($observer);
        unset($this->observers[$id]);
    }
    
    public function getVariable()
    {
        return $this->variable;
    }
    
    public function notify()
    {
        foreach ($this->observers as $observer) {
            $observer->update($this);
        }
    }
    
    public function setVariable($value)
    {
        $this->variable = $value;
        $this->notify();
    }
}

class ConcreteObserverA implements SplObserver
{
    public function update(SplSubject $subject)
    {
        echo 'ConcreteObserverA received: ' . $subject->getVariable() . "\n";
    }
}

class ConcreteObserverB implements SplObserver
{
    public function update(SplSubject $subject)
    {
        echo 'ConcreteObserverB received: ' . $subject->getVariable() . "\n";
    }
}

$subject = new Subject();
$subject->attach(new ConcreteObserverA());
$subject->attach(new ConcreteObserverB());
$subject->setVariable(42);
L'exemple affiche :
ConcreteObserverA received: 42
ConcreteObserverB received: 42