K
- type of the key to identify a cached value. It should be an
immutable type. It is critical this type implements equals() and
hashCode() correctly.V
- type of the cached value.public interface Cache<K,V>
Caches usually makes temporal and/or spatial considerations to clear values.
Use the proxy pattern to incorporate a cache. The proxy would get values
from the cache and it would delegate in case the value is not contained in
the cache. Example:
public interface MyService {
public MyCacheable getCacheable(MyKey key);
}
public class MyServiceCacheProxy implements MyService {
private MyService delegate;
private Cache cache;
public MyServiceCacheProxy(MyService subject) {
this.delegate = subject;
this.cache = ...;
}
@Override
public MyCacheable getCacheable(MyKey key) {
MyCacheable result = this.cache.get(key);
if(result == null) {
result = this.delegate.getCacheable(key);
if(result != null) {
this.cache.put(key, result);
}
}
return result;
}
}
V get(K key)
key
- value's key.null
otherwise.void invalidate(K key)
key
- key to invalidate.void clear()
Copyright © 2015. All Rights Reserved.