Java Observer Update功能 [英] Java Observer Update function

查看:601
本文介绍了Java Observer Update功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现观察者的类,当然它需要具有更新功能:

I have a class that implements observer, and of course it needs to have the update function:

public void update(Observable obs, Object obj);

有人可以解释这两个参数代表什么?
Observable当然是我的可观察对象,但是,如何通过这个Observable obs对象访问我的可观察字段?
什么是对象obj?

Can someone please explain what do the two parameters stand for? Observable is my observable of course, but, how can I access my observable fields through this Observable obs object? And what is Object obj?

推荐答案

如果其他人在确定如何发送第二个时遇到困难参数,就像尼克指出的那样:在 notifyObservers 方法调用中。

In case anybody else is experiencing difficulty in figuring out how to send that second parameter, it is as Nick points out: In the notifyObservers method call.

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

这篇关于Java Observer Update功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆