Design Patterns PHP - Observer Java

1) At the beginning

Let's imagine that we have some class called "ClassA" which has method "changeState"

Objects of "ClassB" and "ClassC" also has interested in state of "ClassA"


2) What do we do?

We create object "ClassA" inject into it objects of "ClassB" and "ClassC"

And after changing state we call notification on these objects. Let's see code:


class ClassA
{
    /**
     * @var ClassB
     */
    protected $classB;

    /**
     * @var ClassC
     */
    protected $classC;

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

    /**
     * @param \ClassB $classB
     * @return \ClassA
     */
    public function setClassB($classB)
    {
        $this->classB = $classB;

        return $this;
    }

    /**
     * @param \ClassC $classC
     * @return \ClassA
     */
    public function setClassC($classC)
    {
        $this->classC = $classC;

        return $this;
    }
}

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

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

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

$classA->setClassB($classB);
$classA->setClassC($classC);

$classA->changeState();




3) Is it proper solution?

It's quite good solution but has cons

If we would like to "ClassA" inform next classes of his state we need to create another setters. And we need to add notification in method "changeState"

4) What we can do ?

We can dynamically attach object of "ClassB" and "ClassC" and other to "ClassA".
Let's do common interface for "ClassB" and "ClassC" and call it "Observer"
In "ClassA" we would send notification for whole list of observers.