我有一个实现观察者的类,当然它需要有更新功能:
public void update(Observable obs, Object obj);
Run Code Online (Sandbox Code Playgroud)
有人可以解释这两个参数代表什么?Observable当然是我的可观察对象,但是,如何通过这个Observable obs对象访问我的可观察字段?什么是Object obj?
obs是扩展Observable并具有notifyObservers方法的对象。您可以转换obs为扩展的对象,Observable然后调用所需的方法。
obj是可以传递给 的可选参数notifyObservers。
如果其他人在确定如何发送第二个参数时遇到困难,那就像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
}
Run Code Online (Sandbox Code Playgroud)
在观察者中:
@Override
public void update(Observable obs, Object arg) {
if (obs instanceof QlmLicense) {
setValid((Boolean) arg);
}
}
Run Code Online (Sandbox Code Playgroud)
请务必正确连接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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9355 次 |
| 最近记录: |