简体   繁体   中英

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

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.)

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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