Best way to notify observers in MVC?

Say that you have 5 or 6 variables in the model that is interested in a particular view, you write different functions for each, for example

int a;
int b;
int c;

void setA( newA ) {
   a = newA;
   notifyAObservers();
}

void setB( newB ) {
   b = newB;
   notifyBObservers();
}

void setC( newC ) {
   b = newC;
   notifyCObservers();
}

Or you only have one notification method and spend a little CPU time

i.e. instead of notifyAObservers and notifyBObservers you just have notifyObservers

+3
source share
2 answers

, . , , , - , , - . , , , , - , .

Observer update(), . Observables ( ) notifyObservers(), update(). .

, , Observer, . , , , - .
+6

EDIT: . , , .

, , , .

. , "args" , ( ).

, , , .

:

public class MyModelV1 extends Observable {
    private int value;
    public void setValue(int value) {
        this.value = value;
        setChanged();
        notifyObservers();
    }
    public int getValue() {
        return value;
    }
}
public class MyViewV1 implements Observer {
    public void update(Observable o, Object arg) {
        if (o instanceof MyModelV1) {
            System.out.println(((MyModelV1) o).getValue());
        }
    }
}

. , , .

:

public class MyModelV2 extends Observable {
    private int value;
    public void setValue(int value) {
        this.value = value;
        setChanged();
        notifyObservers("value");
    }
    public int getValue() {
        return value;
    }
}
public class MyViewV2 implements Observer {
    public void update(Observable o, Object arg) {
        if (o instanceof MyModelV2 && "value".equals(arg)) {
            System.out.println(((MyModelV2) o).getValue());
        }
    }
}

, , . - , , arg ( ).

- - :

public class MyModelV3 extends Observable {
    private int value;
    public void setValue(int value) {
        this.value = value;
        setChanged();
        Notification.MY_MODEL_VALUE_UPDATED.notifyObserver(this);
    }
    public int getValue() {
        return value;
    }
}
public class MyViewV3 implements Observer {
    public void update(Observable o, Object arg) {
        if (Notification.MY_MODEL_VALUE_UPDATED.equals(arg)) {
            MyModelV3 model = Notification.MY_MODEL_VALUE_UPDATED.getModel(o);
            System.out.println(model.getValue());
        }
    }
}
public class Notification<T extends Observable> {
    public static final Notification<MyModelV3> MY_MODEL_VALUE_UPDATED = new Notification<MyModelV3>();
    private Notification() {
    }
    public T getModel(Observable o) {
        return (T) o;
    }
    public void notifyObserver(T observable){
        observable.notifyObservers(this);
    }
}

, . ( ).

- .

0

Source: https://habr.com/ru/post/1714637/


All Articles