Java Observer Update function

后端 未结 3 616
陌清茗
陌清茗 2021-01-03 09:16

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

public void update(Observable obs, Object obj);
<
相关标签:
3条回答
  • 2021-01-03 09:35

    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.

    In the 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
    }
    

    In the Observer:

    @Override
    public void update(Observable obs, Object arg) {
        if (obs instanceof QlmLicense) {
            setValid((Boolean) arg);
        }
    }
    

    Be sure to wire up your Observable correctly, else your update method will not get called.

    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);
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 09:35

    The observer's update(Observable obs,Object obj) method receives through the notifyObservers the object(second parameter) who has changed(in the Observable).

    0 讨论(0)
  • 2021-01-03 09:58

    obs is the object that extends Observable and has the notifyObservers method. You can cast obs to your object that extends Observable and then call the methods you need. obj is the optional parameter that can be passed to notifyObservers.

    0 讨论(0)
提交回复
热议问题