How do I know the generic object that the Observer class sends in Java?

心已入冬 提交于 2019-12-06 19:10:27

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.

You could use instanceof to see what type is your object but you are misusing the pattern.
The idea is that the Observable has a well defined interface and all the Observer needs to know is to use the API to pass the notification.
Logic to know what exactly is the Observable should not be mixed in the code.
From your question sounds to me you have 2 Observable and they should keep their own listeners interested specifically in them for notification. Not one combined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!