Claudio
Claudio

Reputation: 97

MVC Model to View event dispatch implementation

The MVC pattern wants that Model dispatches change status events to View. Which is the best implementation of this comunication if the Model is a simple javabean with setter and getter methods?

Upvotes: 1

Views: 1311

Answers (2)

Peter Walser
Peter Walser

Reputation: 15706

In your bean, allow the registration of PropertyChangeListeners, it's the designated observer class for change notification on java beans.

Example bean with PropertyChangeListener support:

public class TestBean {

    private transient final List<PropertyChangeListener> listeners = new ArrayList<PropertyChangeListener>();

    private String name;

    public void addPropertyChangeListener (PropertyChangeListener listener) {
        listeners.add(listener);
    }

    public void removePropertyChangeListener (PropertyChangeListener listener) {
        listeners.remove(listener);
    }

    private void firePropertyChange (String property, Object oldValue, Object newValue) {

        if (oldValue == newValue || oldValue != null && oldValue.equals(newValue)) {
            return;
        }

        PropertyChangeEvent evt = new PropertyChangeEvent(this, property, oldValue, newValue);
        for (PropertyChangeListener listener : new ArrayList<PropertyChangeListener>(listeners)) {
            listener.propertyChange(evt);
        }
    }

    public String getName () {
        return name;
    }

    public void setName (String name) {

        firePropertyChange("name", this.name, this.name = name);
    }
}

Upvotes: 3

Scharrels
Scharrels

Reputation: 3055

Look at the Observer Pattern for the communication between the Model and the View. The Model should be the Observable and the View should be the Observer.

Upvotes: 1

Related Questions