Design Patterns Java - Observer Php

1) What have we done?

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


import java.util.HashSet;
import java.util.Set;

public class ClassA implements Observed
{
    Set<Observer> observerSet = new HashSet<>();

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

    @Override
    public void addObserver(Observer observer)
    {
        observerSet.add(observer);
    }

    @Override
    public void removeObserver(Observer observer)
    {
        observerSet.remove(observer);
    }

    protected void notifyObservers()
    {
        observerSet.stream().forEach(Observer::changedStateOfClassA);
    }
}

public interface Observed
{
    void addObserver(Observer observer);

    void removeObserver(Observer observer);
}




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


public interface Observer
{
    void changedStateOfClassA();
}

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

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




2) What are pros of this solution?

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


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

        classA.addObserver(classB);
        classA.addObserver(classC);

        classA.changedState();
    }
}