Domanda

È disponibile una versione di uno java.beans.PropertyChangeSupport o com.jgoodies.binding.beans.ExtendedPropertyChangeSupport che è utile per sostenere gli ascoltatori di cambiamento lungo le linee di una mappa o EnumMap? (Un negozio di valori-chiave con note chiavi limitate e gli ascoltatori di cambiamento per tutti i valori nella mappa)

Non ho davvero bisogno di accedere fagioli-tipo, ho un certo numero di diverse statistiche un po 'come:

interface hasName() {
    public String getName();
}

enum StatisticType implements hasName {
    MILES_DRIVEN, BURGERS_SERVED, CUSTOMERS_HELPED, BIRDS_WATCHED;
    @Override public String getName() { return name(); }
}

dove voglio pubblicare un'interfaccia simile:

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()
     */
}

in modo da poter utilizzare un KeyValueStore<StatisticType, Integer> nella mia applicazione.

C'è un modo conveniente per fare questo? Mi gira la testa in cerchio ed è fiaccando la mia energia cercando di reinventare la ruota su questa roba.

È stato utile?

Soluzione

A meno che non ci sia una ragione pressante di non farlo, vorrei estendere Map e utilizzare put e get invece di setValue e getValue.

Ho un'interfaccia che uso spesso:

public interface PropertyChangeNotification {
    void addPropertyChangeListener(String property, PropertyChangeListener listener);
    void removePropertyChangeListener(String property, PropertyChangeListener listener);
    void addPropertyChangeListener(PropertyChangeListener listener);
    void removePropertyChangeListener(PropertyChangeListener listener);
}

Con questo, l'interfaccia diventa:

interface KeyValueStore<K extends hasName,V>
    extends Map<K,V>, PropertyChangeNotification
{
}

Poi l'implementazione finisce per guardare qualcosa di simile:

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);
    }
}

Non mostrato sono i 4 metodi per la funzionalità PropertyChangeNotification che semplicemente delegare a changer.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top