简体   繁体   中英

Observer Pattern - Update method parameter

I am trying to use the properties of the object that is passed into the notifyObservers method, but I can't seem to find a way to access them. I can only pass in a single string, but I want more options to be passed into the observer.

This is a sample of the setup;

public class UpdateInfo {

          public String data;
          public int debug = 0;
}

public class RXTXComms extends Observable {

         UpdateInfo info = new UpdateInfo();

         public void sendToBoard(String s) {
                .......

                UpdateInfo.data = "test";
                UpdateInfo.debug = 1;
                stChanged();
                notifyObservers(info);
          }  
}

public class Program implements Observer {

     public void update(Observable obj, Object arg) {
            String msg = ""; // Message to display on GUI

            if (arg instanceof UpdateInfo) {
                 //Print out the message and Debug int onto GUI...but how do I access them from `arg`
        }
    }

}

If I make the type of arg to be UpdateInfo , then I get a compiler error that my class Program is not abstract....

Is this not an honest, appropriate question?

You need to cast the class.

 UpdateInfo ui = (UpdateInfo) arg;

inside your instanceof should do the trick.

The Observable / Observer API of Java is really badly designed, don't use it. Seriously - it should not have been an abstract class, but an interface.

The observer pattern is so simple, just implement it on your own with full type safety . It actually does not pay off to even specify a better interfaced version of it. The various Listener s for example are just another instance of this pattern in Java that is much better executed: the listeners have methods with good method names and extra data, and there exists an abstract Adapter if there is more than one method to implement and you will often not need all of them (see eg MouseAdapter ).

So re-implement the pattern for a concrete use case , not for the unspecified "if anything happens" case. Patterns are actually meant to be reimplemented, not abstractly inherited from a pattern library.

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