加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Java Observer Update功能

发布时间:2020-12-15 04:59:33 所属栏目:Java 来源:网络整理
导读:我有一个实现观察者的类,当然它需要有更新功能: public void update(Observable obs,Object obj); 有人可以解释这两个参数代表什么? Observable当然是我的可观察对象,但是,如何通过这个Observable obs对象访问我的可观察字段? 什么是Object obj? 解决方
我有一个实现观察者的类,当然它需要有更新功能:

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);
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读