Design Patterns PHP - Observer Java

1) What have we done?

For "ClassA" we created interface which two methods: "addObserver" and "removeObserver" adding and removing observers


class ClassA implements Observed
{
    /**
     * @var Observer[]
     */
    protected $observers = [];

    public function changeState()
    {
        echo 'ClassA change state' . PHP_EOL;
        $this->notify();
    }

    /**
     * @param Observer $observer
     * @return ClassA
     */
    public function addObserver(Observer $observer)
    {
        $this->observers[] = $observer;

        return $this;
    }

    /**
     * @param Observer $observer
     * @return ClassA
     */
    public function removeObserver(Observer $observer)
    {
        if (isset($this->observers[array_search($observer, $this->observers)]))
            unset($this->observers[array_search($observer, $this->observers)]);

        return $this;
    }

    protected function notify()
    {
        foreach ($this->observers as $observer) {
            $observer->changedStateOfClassA();
        }
    }
}

interface Observed
{
    public function addObserver(Observer $observer);

    public function removeObserver(Observer $observer);
}




"Observer" objects implement one method which is called by "Observed" object


interface Observer
{
    public function changedStateOfClassA();
}

class ClassB implements Observer
{
    public function changedStateOfClassA()
    {
        echo 'ClassB: ClassA changed state' . PHP_EOL;
    }
}

class ClassC implements Observer
{
    public function changedStateOfClassA()
    {
        echo 'ClassC: ClassA changed state' . PHP_EOL;
    }
}




2) What are pros of this solution?

Now we can easily in dynamically way attach many observers without changing "Observed" code


$classA = new ClassA();
$classB = new ClassB();
$classC = new ClassC();

$classA->addObserver($classB);
$classA->addObserver($classC);

$classA->changeState();