I am trying to implement Decorator design pattern for HashMap.
I have two Decorators - "UpperCaseHashMap" and "AddHashMap".
However, the result map contains only the effect of one of the decorators, example :-
Map<String, String> map = new AddHashMap<>(new UpperCaseHashMap<>(new HashMap<> ()));
map.add("aa", "aa");
System.out.println(map);
-
Only AddHashMap effect i.e. result is - {AA=AA}
Map<String, String> map = new UpperCaseHashMap<>(new AddHashMap<>(new HashMap<> ())); map.add("aa", "aa"); System.out.println(map);
-
Only UpperCaseHashMap effect i.e. result is - {aaADDED_BY_DECORATOR=aa}
Below is the code of the decorator classes:-
public class UpperCaseHashMap<K, V> extends HashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = 1L;
Map<K, V> map;
public UpperCaseHashMap() {
map = new HashMap<>();
}
UpperCaseHashMap(Map<K, V> map) {
this.map = map;
}
public V put(K key, V value) {
String temp = key.toString().toUpperCase();
key = (K) temp;
return super.put(key, value);
}
}
public class AddHashMap<K, V> extends HashMap<K, V> {
/**
*
*/
private static final long serialVersionUID = 1L;
Map<K, V> map;
AddHashMap(Map<K, V> map) {
this.map = map;
}
public V put(K key, V value) {
String temp = key.toString().concat("ADDED_BY_DECORATOR");
key = (K) temp;
return super.put(key, value);
}
}
Aucun commentaire:
Enregistrer un commentaire