Search code examples
javaswingarraylistlistenerobserver-pattern

Should I use a Listener or Observer?


I have a dropdown box in my GUI which shows the contents of an ArrayList in another class. New objects can be added to the ArrayList elsewhere in the GUI, so I need to know when it is updated, so I can refresh the dropdown menu. From what I can gather, my two options are to extend the ArrayList class to allow me to add my own changeListener to it, or to make the class which contains the ArrayList in question extend observable.

Which would be a more appropriate solution?


Solution

  • The two solutions are essentially implementations of the same root design pattern (the "Observer" pattern as defined by the Gang of Four.) In the former case, you are making the ArrayList itself "observable", in the latter you are making the domain object which uses the array list "observable."

    My tendency would be to do the latter: make the domain object observable. This is primarily because you may eventually have other things that could change about the domain object (for which the GUI should be updated.) If it is already observable, you're already set.

    Note that you don't strictly have to extend java.util.Observable - you can implement the design pattern without doing that.