mardi 16 mars 2021

Implementation of Observer Pattern Based on UML diagram

Question

I'm having trouble understanding the following UML-diagram of the observer-pattern from the "Elements of Reusable Object-Oriented Software". Could you explain me why my Java-Implementation is wrong and what I have to change to implement it correctly?

UML-Diagram

UML-Diagram

Attempted (but wrong) implementation

public interface Subject {
    
    public static final List<Observer> observers = new ArrayList<Observer>();
    
    public void attach(Observer o);
    public void detach(Observer o);
    public void notifyObservers();

}

public interface Observer {
    
    public void update();

}

public class ConcreteSubject implements Subject {
    
    private String subjectState;

    @Override
    public void attach(Observer o) {
        observers.add(o);   
    }

    @Override
    public void detach(Observer o) {
        observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer o : observers) {
            o.update();
        }
        
    }
    
    public String getState() {
        return subjectState;
    }
    
    public void setState() {
        subjectState += "x";
    }

}

public class ConcreteObserver implements Observer {
    
    private ConcreteSubject subject;
    public String observerState;

    @Override
    public void update() {
        observerState = subject.getState();
    }

}

Aucun commentaire:

Enregistrer un commentaire