简体   繁体   English

具有多个可观察的单个观察者

[英]Single observer with multiple observable

I would like to know what would be the implementation with respect to observer design pattern. 我想知道观察者设计模式的实现是什么。 Like generally we maintain a list of observers in Observable and from its notify we call the update method of the observers. 通常我们在Observable中维护一个观察者列表,并从其通知中调用观察者的更新方法。

Now what would be the design in this case? 那么这种情况下的设计是什么? Should i maintain a list of observable in the observers? 我应该在观察员中保留一个可观察的清单吗? But then in the update method how i would know which observable has called the update on this observer. 但是在更新方法中我怎么知道哪个observable调用了这个观察者的更新。

Please share your idea on this. 请分享您的想法。

Thanks, 谢谢,

Usually the observable hold a reference to the observer. 通常,观察者持有对观察者的引用。 in your case this mightg be a list. 在你的情况下,这可能是一个列表。 in any case, the first argument to update is the observable. 在任何情况下,更新的第一个参数是可观察的。

So this is one way: 所以这是一种方式:

import java.util.Observable;
import java.util.Observer;
enum Observables {
    o1,o2
}
class MyObservable extends Observable {
    public MyObservable(Observables observables) {
        this.observables=observables;
    }
    public void setChangedAndNotify(Object object) {
        setChanged();
        notifyObservers(object);
    }
    final Observables observables;
}
class MyObserver implements Observer {
    @Override public void update(Observable o,Object arg) {
        switch(((MyObservable)o).observables) {
            case o1:
                System.out.println(((MyObservable)o).observables);
                break;
            case o2:
                System.out.println(((MyObservable)o).observables);
                break;
        }
    }
}
class so56200126_single_observer_with_multiple_observable {
    public static void main(String[] args) throws InterruptedException {
        MyObservable myObservable1=new MyObservable(Observables.o1);
        MyObservable myObservable2=new MyObservable(Observables.o2);
        MyObserver myObserver=new MyObserver();
        myObservable1.addObserver(myObserver);
        myObservable2.addObserver(myObserver);
        myObservable1.setChangedAndNotify(null);
        myObservable2.setChangedAndNotify(null);
        Thread.sleep(1);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM