package envoy.client.data;
import java.io.Serializable;
import java.util.*;
/**
* Stores a heterogeneous map of {@link Cache} objects with different type
* parameters.
*
* Project: envoy-client
* File: CacheMap.java
* Created: 09.07.2020
*
* @author Kai S. K. Engelbart
* @since Envoy Client v0.1-beta
*/
public final class CacheMap implements Serializable {
private final Map, Cache>> map = new HashMap<>();
private static final long serialVersionUID = 1L;
/**
* Adds a cache to the map.
*
* @param the type accepted by the cache
* @param key the class that maps to the cache
* @param cache the cache to store
* @since Envoy Client v0.1-beta
*/
public void put(Class key, Cache cache) { map.put(key, cache); }
/**
* Returns a cache mapped by a class.
*
* @param the type accepted by the cache
* @param key the class that maps to the cache
* @return the cache
* @since Envoy Client v0.1-beta
*/
public Cache get(Class key) { return (Cache) map.get(key); }
/**
* Returns a cache mapped by a class or any of its subclasses.
*
* @param the type accepted by the cache
* @param key the class that maps to the cache
* @return the cache
* @since Envoy Client v0.1-beta
*/
public Cache super T> getApplicable(Class key) {
Cache super T> cache = get(key);
if (cache == null) for (final var e : map.entrySet())
if (e.getKey().isAssignableFrom(key)) cache = (Cache super T>) e.getValue();
return cache;
}
/**
* @return the map in which the caches are stored
* @since Envoy Client v0.1-beta
*/
public Map, Cache>> getMap() { return map; }
/**
* Clears the caches of this map of any values.
*
* @since Envoy Client v0.2-beta
*/
public void clear() { map.values().forEach(Cache::clear); }
}