package lc.mecha.lang;

import java.util.HashMap;

/**
 * This class acts as {@link HashMap} except that if <code>get()</code> is called and there is no matching
 * entry, one is created and returned. This operation is synchronized.
 *
 * @author Alex Leigh
 * @since mk12 mod10 (RETROGRADE)
 */

public class FactoryMap<K, V> extends HashMap<K, V> {
    private final Factory<V> factory;


    public FactoryMap(Factory<V> factory) {
        this.factory = factory;
    }

    public synchronized V get(final Object key) {
        V obj = super.get(key);
        if (obj == null) {
            obj = factory.create();
            super.put((K) key, obj);
        }
        return obj;
    }
}
