[英]Java Observer Update 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中)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.