tags:

views:

6

answers:

0

I'm building a GUI application and try to adhere to the MVC principle as good as I can.

Therefore my model fires PropertyChangeEvents with the help of PropertyChangeSupport so the GUI knows what to update when.

The model of my application is nested, i.e. I have a main model class that contains some properties or Lists of other model classes which in turn might contain more model classes.

A simple example:

public class MainModel {
    private int someData;
    private List<Stuff> stuffList;
    // imagine PropertyChangeSupport and appropriate getters/setters
    // for both MainModel and Stuff
}

Now both MainModel and Stuff have PropertyChangeSupport. If someone listens to events fired from MainModel, it gets changes of someData and from adding/deleting to/from the list stuffList.

But what if someone wants to get events from changes made to the individual elements of stuffList? There are two possibilities:

  1. The observer has to fetch the list of Stuff elements and register as a listener to each element separately.
  2. The main model registers itself as a listener to the elements of stuffList when they are added and forwards these events to the listener of the main model.

This is how it looks like with the first approach:

mainModelInstance.addListener("new stuff element", new PropertyChangeListener() {
    public void propertyChanged(PropertyChangeEvent evt) {
        Stuff s = (Stuff) evt.getNewValue();
        s.addListener( // ... and so on
        );
    }
});

I think 1. has the advantage of keeping the model clean and dumb but leads to code duplication (many UI elements have to listen to changes to stuffList and add themselves dynamically to the new Stuff elements, see above). With 2. its the opposite: The client code is not as messy but the model acts partly as a listener which somehow doesn't feel right. That's why I currently use the first approach.

What are your thoughts? Maybe I'm too harsh on myself and 2. is okay. Or maybe there is a completely different (and better) way?