How to observe multiple data of same class in Java

2019-07-21 05:52发布

Here's 2 option that i thought of.

  1. Have multiple models each representing one class. If i have 2 int object, i need to create 2 observable and have view checking which observable is changed.

  2. In a single observable (model), group multiple object of the same class into Array. In view i will have to iterate the array and change all fields containing all data in the array.

I am starting to learn how to implement MVC pattern, using java observable and observer. I find the 2 methods which i have mentioned is not the best solution. Hope can get some help on this.

Edit: Example, i have the following methods in observable class, can someone show me how to write the update() in observer to get the value of int b?

public void setIntA(int a){
     this.intA = a;
     setChanged();
     notifyObservers(a);
}
public void setIntB(int b){
     this.intB = b;
     setChanged();
     notifyObservers(b);
}
setIntA(5);
setIntB(3);

2条回答
forever°为你锁心
2楼-- · 2019-07-21 06:11

Create two references on the Observer class to a and be and you can use update command like this.

public void update(Observable o, Object arg)
{
  if (o == a)
  {
     //do what you want with arg
  }
}
查看更多
闹够了就滚
3楼-- · 2019-07-21 06:24

I'm not exactly sure what you are trying to do here but if you have a class that extends Observable then it can fire a change event for any number of reasons. If you just want to notify observers when any value changes then you just need to call setChanged() and notifyObservers() in the setter. Like Thilo said, you can pass the thing that changed as a parameter of notifyObservers();

public void setIntA(int a){
     this.intA = a;
     setChanged();
     notifyObservers(a);
}

I suggest you make sure you read the Javadoc thoroughly to get the best understanding of Observer and Observable.

查看更多
登录 后发表回答