问题描述
我正在使用Java实现Observer / Observable模式。但是,我在代码的Observer部分遇到问题。
可观察
public class Model extends Observable {
public void notify(){
this.setChanged();
this.notifyObservers(new ArrayList< A>());
this.notifyObservers(new ArrayList< B>());
}
}
观察者
public class View实现Observer {
@Override
public void update(Observable observable,Object object ){
// TODO:如果object是ArrayList< A> ;?
System.out.println(A);
// TODO:如果object是ArrayList< B> ;?
System.out.println(B);
我会如何填写TODO评论以检查ArrayList上的泛型?这甚至有可能吗? (如果可能,我宁愿不执行更多的类。)
的数据。 public class ModelA extends Observable {
public void notify(){
this.setChanged();
this.notifyObservers(new ArrayList< A>());
public class ModelB extends Observable {
public void notify(){
this.setChanged();
this.notifyObservers(new ArrayList< B>());
}
}
另一种方法是将ArrayList< A&和ArrayList< B>成为一个班级。您可以通知您的观察员使用该类。
I am implementing the Observer / Observable pattern using Java. However, I am encountering a problem in the Observer portion of my code.
Observable
public class Model extends Observable {
public void notify() {
this.setChanged();
this.notifyObservers(new ArrayList<A>());
this.notifyObservers(new ArrayList<B>());
}
}
Observer
public class View implements Observer {
@Override
public void update(Observable observable, Object object) {
// TODO: If object is ArrayList<A>?
System.out.println("A");
// TODO: If object is ArrayList<B>?
System.out.println("B");
}
}
How would I fill in the TODO comments to check for the generic on the ArrayList? Is this even possible? (I would prefer to do it without implementing more classes, if possible.)
An Observable should send one and only one type of data.
public class ModelA extends Observable {
public void notify() {
this.setChanged();
this.notifyObservers(new ArrayList<A>());
}
}
public class ModelB extends Observable {
public void notify() {
this.setChanged();
this.notifyObservers(new ArrayList<B>());
}
}
Your other alternative is to put ArrayList<A> and ArrayList<B> into a class. You can notify your observers with that class.
这篇关于我如何知道Observer类在Java中发送的通用对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!