Design Patterns Java - Observer Php

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:


public class ClassA
{
    protected ClassB classB;

    protected ClassC classC;

    public void changedState()
    {
        System.out.println("ClassA is changing state");
        classB.changedStateOfClassA();
        classC.changedStateOfClassA();
    }

    public void setClassB(ClassB classB)
    {
        this.classB = classB;
    }

    public void setClassC(ClassC classC)
    {
        this.classC = classC;
    }
}

public class ClassB
{
    public void changedStateOfClassA()
    {
        System.out.println("ClassB: ClassA has changed state");
    }
}

public class ClassC
{
    public void changedStateOfClassA()
    {
        System.out.println("ClassC: ClassA has changed state");
    }
}

public class Client
{
    public static void main(String[] args)
    {
        ClassA classA = new ClassA();
        ClassB classB = new ClassB();
        ClassC classC = new ClassC();

        classA.setClassB(classB);
        classA.setClassC(classC);

        classA.changedState();
    }
}




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.