java Cache

1 interface
public interface Cache<K, I> {

public boolean addItem(K key, I item);

public I getItem(K key);

public Map<K, I> getItems();

public boolean containsKey(K key);
}

2 abstract
public abstract class AbstractCache<K, I> implements Cache<K, I> {

}


3 <1>implement
public class PricesCache<K, I> extends AbstractCache<K, I> {

private Map<K, I> cacheMap = null;

public PricesCache() {
cacheMap = new HashMap<K, I>();
}

public boolean addItem(K key, I item) {
return cacheMap.put(key, item) != null;
}

public I getItem(K key) {
return cacheMap.get(key);
}

public boolean containsKey(K key) {
return cacheMap.containsKey(key);
}

public Map<K, I> getItems() {
return cacheMap;
}
}

3 <2>implement
public class ProductsCache<K, I> extends AbstractCache<K, I> {

private Map<K, I> cacheMap = null;

public ProductsCache() {
cacheMap = new HashMap<K, I>();
}

public boolean addItem(K key, I item) {
return cacheMap.put(key, item) != null;
}

public I getItem(K key) {
return cacheMap.get(key);
}

public boolean containsKey(K key) {
return cacheMap.containsKey(key);
}

public Map<K, I> getItems() {
return cacheMap;
}
}

原文地址:https://www.cnblogs.com/rojas/p/4341005.html