001/*
002 *                    BioJava development code
003 *
004 * This code may be freely distributed and modified under the
005 * terms of the GNU Lesser General Public Licence.  This should
006 * be distributed with the code.  If you do not have a copy,
007 * see:
008 *
009 *      http://www.gnu.org/copyleft/lesser.html
010 *
011 * Copyright for this code is held jointly by the individual
012 * authors.  These should be listed in @author doc comments.
013 *
014 * For more information on the BioJava project and its aims,
015 * or to join the biojava-l mailing list, visit the home page
016 * at:
017 *
018 *      http://www.biojava.org/
019 *
020 */
021
022package org.biojava.utils.cache;
023
024import java.util.HashMap;
025import java.util.Map;
026
027import org.biojava.utils.ChangeAdapter;
028import org.biojava.utils.ChangeEvent;
029import org.biojava.utils.ChangeListener;
030import org.biojava.utils.ChangeType;
031import org.biojava.utils.Changeable;
032
033/**
034 * A cache that clears values as the keys fire ChangeEvents of a given type.
035 *
036 * @author Matthew Pocock
037 * @since 1.1
038 */
039
040public class ChangeableCache {
041  private ChangeType changeType;
042  private Map cache = new HashMap();
043  private ChangeListener listener = new ChangeAdapter() {
044    public void postChange(ChangeEvent ce) {
045      Changeable source = (Changeable) ce.getSource();
046      cache.remove(source);
047      source.removeChangeListener(listener);
048    }
049  };
050  
051  public ChangeableCache(ChangeType ct) {
052    this.changeType = ct;
053  }
054  
055  public void put(Object key, Object value) {
056    cache.put(key, value);
057    if(key instanceof Changeable) {
058      ((Changeable) key).addChangeListener(listener, changeType);
059    }
060  }
061  
062  public Object get(Object key) {
063    return cache.get(key);
064  }
065}