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?
+1
A:
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.
Scharrels
2009-12-10 10:59:52
+1
A:
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);
}
}
Peter Walser
2009-12-10 11:28:55
I prefer this answer because it tells me not only how to dispatch the event, but also how to report to listeners witch attribute has been changed.
Claudio
2009-12-10 11:34:55