我有3个类,Manager,MessageObserver,WidgetObserver
当我调用testManager()时,我得到MessageObserver中的update()方法来触发,但MessageObserver中的notifyObservers()方法不会触发WidgetObserver中的update()方法。
public Manager extends Observable
{
private ArrayList<Observer> observers = new ArrayList<>();
public Manager()
{
// Set local variables
}
public void addObserver(Observer o)
{
observers.add(o);
}
public void newMessage(String a1, String a2)
{
this.a1 = a1;
this.a2 = a2;
setChanged();
notifyObservers();
}
}
public MessageObserver extends Observable implements Observer
{
private ArrayList<Observer> observers = new ArrayList<>();
public MessageObserver(Manager aManager)
{
mManager = aManager;
mManager.addObserver(this);
// set local variables from mManager.getValues()
}
public void update(Observable obj, Object arg)
{
System.out.println("Triggered MessageObserver");
...
setChanged();
notifyObservers();
}
}
public WidgetObserver implements Initializable, Observer
{
public WidgetObserver()
{
mManager= new Manager();
mMessageObserver = new MessageObserver(mManager);
mMessageObserver.addObserver(this);
}
public void initialize()
{
// Establish local variables
testManager();
}
private void testManager()
{
mManager.newMessage(...);
}
public void update(Observable obj, Object arg)
{
System.out.println("WIDGET TRIGGERED");
// Add value to local array
}
}
答案 0 :(得分:1)
一个猜测将Observer的列表为null所以请检查你是否注册了Observer.In你的代码观察者列表与observable不同。
Observable中的逻辑
if (!changed)
return;
arrLocal = obs.toArray();
clearChanged();
}
for (int i = arrLocal.length-1; i>=0; i--)
((Observer)arrLocal[i]).update(this, arg);