I'm aware of the use of the pattern observer but for the moment I'm seeing that it's a useless layer to do operations on observer objets while you can do the same operation without the need to use this design pattern !
Can somebody correct me if I'm wrong and explain to be using a concret example the utility and the importance of this design pattern ?
I can see that it offers more code organisation but when should I use it ?
For example here's an implementation of the Observer pattern in PHP :
Here's the observed or the subject class
// Dès que cet attribut changera on notifiera les classes observatrices.
protected $name;
public function attach(SplObserver $observer)
{$this->observers[] = $observer;
}
public function detach(SplObserver $observer)
{
if (is_int($key = array_search($observer, $this->observers, true)))
{
unset($this->observers[$key]);
}
}
public function notify()
{
foreach ($this->observers as $observer)
{
$observer->update($this);
}
}
public function getName()
{
return $this->name;
}
public function setNom($name)
{
$this->name = $name;
$this->notify();
}
}
Here are the observers containing the actions made when they're notified :
<?php
class Observer1 implements SplObserver
{
public function update(SplSubject $obj)
{
echo 'Observer1 has been notified! Nouvelle valeur de l\'attribut <strong>nom</strong> : ', $obj->getName();
}
}
class Observer2 implements SplObserver
{
public function update(SplSubject $obj)
{
echo 'Observer2 a has been notified! Nouvelle valeur de l\'attribut <strong>nom</strong> : ', $obj->getName();
}
}
And here's how we use them
$o = new Observee;
$o->attach(new Observer1); // Adding an observer.
$o->attach(new Observer2); // Adding another observer.
$o->setNom('Victor'); // We mmofidy this attribute and the observers have taken the speficified action
Now as you can see I don't need to implement the two functions notify() and update() to make the observers take some action.
I don't see which problem does this Design Pattern responds to .