Is there a version of either java.beans.PropertyChangeSupport
or com.jgoodies.binding.beans.ExtendedPropertyChangeSupport
which is helpful for supporting change listeners along the lines of a Map or EnumMap? (a key-value store with known limited keys and change listeners for all the values in the map)
I don't really need beans-type access, I have a number of different statistics sort of like:
interface hasName() {
public String getName();
}
enum StatisticType implements hasName {
MILES_DRIVEN, BURGERS_SERVED, CUSTOMERS_HELPED, BIRDS_WATCHED;
@Override public String getName() { return name(); }
}
where I want to publish an interface like:
interface KeyValueStore<K extends hasName,V>
{
void setValue(K key, V value);
V getValue(K key);
void addPropertyChangeListener(PropertyChangeListener listener);
void removePropertyChangeListener(PropertyChangeListener listener);
/*
* when setValue() is called, this should send PropertyChangeEvents
* to all listeners, with the property name of K.getName()
开发者_开发知识库*/
}
so I could use a KeyValueStore<StatisticType, Integer>
in my application.
Is there any convenient way to do this? My head is spinning around in circles and it's sapping my energy trying to reinvent the wheel on this stuff.
Unless there is a pressing reason not to, I would extend Map
and use put
and get
instead of setValue
and getValue
.
I have an interface I often use:
public interface PropertyChangeNotification {
void addPropertyChangeListener(String property, PropertyChangeListener listener);
void removePropertyChangeListener(String property, PropertyChangeListener listener);
void addPropertyChangeListener(PropertyChangeListener listener);
void removePropertyChangeListener(PropertyChangeListener listener);
}
With that, your interface becomes:
interface KeyValueStore<K extends hasName,V>
extends Map<K,V>, PropertyChangeNotification
{
}
Then your implementation winds up looking something like this:
public class MyKeyStore<K extends hasName, V>
extends HashMap<K,V>
implements KeyValueStore<K,V>
{
private PropertyChangeSupport changer = new PropertyChangeSupport(this);
public void put(K key, V value)
{
V old = get(K);
super.put(key,value);
changer.firePropertyChange(key.getName(), value, old);
}
}
Not shown are the 4 methods for the PropertyChangeNotification functionality that simply delegate to changer
.
精彩评论