mercredi 1 novembre 2017

Observer Uml & Java

I really need your help for a question: the right implementation of pattern Observer. The fact is that I have no guarantees about doing right so I just would like to know if there are inconsistencies between UML and code below, please report me any minimum mistake/improvable detail in both parties. I would be so much grateful to anyone, thanks in advance.

UML:

Observer UML

JAVA CODE:

public interface Subject {
    public void registerObserver(Observer o);
    public void removeObserver(Observer o);
    public void notifyObservers();
}

public class ConcreteSubject implements Subject {
    private int my_state;
    private ArrayList<Observer> observers;
    public ConcreteSubject(){
        observers=new ArrayList<Observer>();
    }
    public void registerObserver(Observer o){
        observers.add(o);
    }
    public void removeObserver(Observer o){
        observers.remove(o);
    }
    public void notifyObservers(){
        for(Observer o : observers)
            o.update();
    }
    //PULL Mode -> Observer musts grab the state of the subject
    public int getState(){
       return my_state;
    }
    public void setState(int state){
        my_state=state;
    }
 }

public interface Observer {
    public void update(); //In PULL mode update don't need the state of the subject in argument
}

public class ConcreteObserver implements Observer {
    private ConcreteSubject my_subject;
    public ConcreteObserver(ConcreteSubject subject){
        my_subject=subject;
    }
    public void update(){
        System.out.println("The state is: "+my_subject.getState());
    }
}

Aucun commentaire:

Enregistrer un commentaire