Decorator Design Pattern with HashMap returning empty HashMap

Your line:

return super.put(key, value);

Is calling HashMap.put irrespective of the implementation of the map passed to the constructor. Instead you need:

return map.put(key, value);

However I feel you are probably misunderstanding how decorators work. If you are using subclassing you will need to forward every method to the delegate. At the moment your classes are extending HashMap but then delegating put specifically. This isn’t going to work. All the other methods are going to go to the extended HashMap and won’t find the data you’ve put into the delegate. You need to rethink your design.

You might want to consider a design like:

@FunctionalInterface
interface MapDecorator<V> {
    V decorate(V value);
}

class DecoratedMap<K, V> extends HashMap<K, V> {
    private final List<MapDecorator<V>> decorators = new ArrayList<>();

    public void addDecorator(MapDecorator<V> decorator) {
        decorators.add(decorator);
    }

    @Override
    public V put(K key, V value) {
        for (MapDecorator<V> decorator: decorators)
            value = decorator.decorate(value);
        return super.put(key, value);
    }
}

I’ve used ‘decorator’ in this code to match your original question but, in reality, this is not using the decorator design pattern so, in reality, I’d use a different name such as ‘transformer’.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top