// 我们也可以直接在需要的时候自行组合,就和标准库里的 InputStream 的用法类似
public static void main(String[] args) {
Multimap<String, Integer> treeMap = new Multimap<>(new DefaultValue<>(k -> new LinkedList<>(), new TreeMap<>()));
treeMap.putItem("Yang's IQ", 200);
}
// 我们可以在默认构造函数里把需要的功能组合起来
public class HashMultimap<K, V> extends MultimapView<K, V> {
public HashMultimap() {
super(new DefaultValueMap<>(k -> new ArrayList<>(), new HashMap<>()));
}
}
// 一个组合子提供一对多的功能
public class MultimapView<K, V> implements Multimap<K, V> {
private final Map<K, Collection<V>> delegate;
public Multimap(Map<K, Collection<V>> delegate) {...}
@Override public putItem(K key, V value) {
delegate.get(key).add(value);
}
@Override delegating all other methods ...
}
// 一个组合子提供默认值的功能
public class DefaultValueMap<K, V> implements Map<K, V> {
private final Function<K, V> defValMaker;
private final Map<K, V> delegate;
public DefaultValueMap(Function<K, V> defValMaker, Map<K, V> delegate) {...}
@Override public get(K key) {
if (!delegate.contains(key)) {
V defaultValue = defValMaker.apply(key);
delegate.put(key, defaultValue);
}
return delegate.get(key);
}
@Override delegating all other methods ...
}