Java Observer Updatefunction
我有一个实现观察者的类,当然它需要有更新function:
public void update(Observable obs, Object obj);
有人可以解释这两个参数代表什么? Observable当然是我的可观察对象,但是,如何通过这个Observable obs对象访问我的可观察字段? 什么是Object obj?
如果其他人在确定如何发送第二个参数时遇到困难,就像Nick指出的那样:在notifyObservers方法调用中。
在Observable中:
private void setLicenseValid(boolean licenseValid) { this.licenseValid = licenseValid; setChanged(); // update will only get called if this method is called notifyObservers(licenseValid); // add parameter for 2nd param, else leave blank }
在观察者中:
@Override public void update(Observable obs, Object arg) { if (obs instanceof QlmLicense) { setValid((Boolean) arg); } }
确保正确连接Observable,否则不会调用更新方法。
public class License implements Observer { private static QlmLicense innerlicense; private boolean valid; private Observable observable; private static QlmLicense getInnerlicense() { if (innerlicense == null) { innerlicense = new QlmLicense(); // This is where we call the method to wire up the Observable. setObservable(innerlicense); } return innerlicense; } public boolean isValid() { return valid; } private void setValid(Boolean valid) { this.valid = valid; } // This is where we wire up the Observable. private void setObservable(Observable observable) { this.observable = observable; this.observable.addObserver(this); } @Override public void update(Observable obs, Object arg) { if (obs instanceof InnerIDQlmLicense) { setValid((Boolean) arg); } } }
obs
是扩展Observable
的对象,并具有notifyObservers
方法。 您可以将obs
为扩展Observable
的对象,然后调用所需的方法。 obj
是可以传递给notifyObservers
的可选参数。
观察者的更新(Observable obs,Object obj)方法通过notifyObservers接收已更改的对象(第二个参数)(在Observable中)。