001// License: GPL. For details, see LICENSE file.
002package org.openstreetmap.josm.data.preferences;
003
004import org.openstreetmap.josm.data.preferences.AbstractProperty.ValueChangeListener;
005
006/**
007 * This is a special wrapper of {@link AbstractProperty}.
008 * The current preference value is cached. The value is invalidated if the preference was changed.
009 * @author Michael Zangl
010 *
011 * @param <T> property type
012 * @since 10824
013 */
014public class CachingProperty<T> extends AbstractProperty<T> implements ValueChangeListener<T> {
015
016    private T cache;
017    private boolean cacheActive;
018    private final AbstractProperty<T> toCache;
019
020    /**
021     * Create a new caching property.
022     * @param toCache The property to cache.
023     */
024    CachingProperty(AbstractProperty<T> toCache) {
025        super(toCache.getKey(), toCache.getDefaultValue());
026        this.toCache = toCache;
027        addWeakListener(this);
028    }
029
030    @Override
031    public synchronized T get() {
032        if (!cacheActive) {
033            cache = toCache.get();
034            cacheActive = true;
035        }
036        return cache;
037    }
038
039    @Override
040    public boolean put(T value) {
041        return toCache.put(cache);
042    }
043
044    @Override
045    public synchronized void valueChanged(ValueChangeEvent<? extends T> e) {
046        cacheActive = false;
047    }
048}