The code you look for is in java.beans.PropertyChangeSupport
. You use it like this:
protected transient PropertyChangeSupport changeSupport = new PropertyChangeSupport (this);
public void addPropertyChangeListener (String propertyName, PropertyChangeListener listener)
{
changeSupport.addPropertyChangeListener (propertyName, listener);
}
public void removePropertyChangeListener (String propertyName, PropertyChangeListener listener)
{
changeSupport.removePropertyChangeListener (propertyName, listener);
}
public void firePropertyChange (String propertyName, BigDecimal oldValue, BigDecimal newValue)
{
if (oldValue != null && newValue != null && oldValue.compareTo (newValue) == 0) {
return;
}
changeSupport.firePropertyChange(new PropertyChangeEvent(this, propertyName,
oldValue, newValue));
}
The main advantage of using this API is that everyone is familiar with it. The main disadvantage is that the Beans API is pretty old, cumbersome from todays point of view and very limiting.
For example, you need the name of a property in many places. This either means you must copy a string (which breaks if you rename the property) or you must manually define a String constant for every field which is tedious.
The implementation itself is pretty fast and follows the Observer design pattern. Of course, there are other ways to implement this. The price would be that this is no longer a bean since it doesn't follow the API. Hence, you can't use your object in many frameworks without additional glue code.