What is the use of ForwardingMap in Guava?

Am I scratching my head about understanding the use of ForwardingMap? What cases can he use?

+6
source share
2 answers
Classes

ForwardingXxx provides a decorator pattern for all JDK and Guava collections, including Map .

Learn more about the Guava wiki and Effective Java 2nd Edition, p. 16: Composition Preference over Inheritance:

To summarize, inheritance is powerful, but it is problematic because it violates encapsulation. This is only relevant when a genuine subtype exists between the subclass and the superclass. Even then inheritance can lead to fragility if the subclass is in a different package from the superclass and the superclass is not intended for inheritance. To avoid this fragility, use composition and forwarding instead of inheritance, especially if the appropriate interface for implementing the wrapper class exists. Not only are wrapper classes more robust than subclasses, they are also more powerful.

This basically allows you to customize a possibly non-extensible Map without adding dependencies on the actual Map implementation.

+15
source

The default classes are final by default. This means that you cannot renew them. When you want to create a map with a specific behavior, you need to write your own class that implements the entire map interface and forwards all the methods to the internal map.

ForwardingMap makes this easier for you, already being an extensible class that implements Map and redirects everything to an internal map. This means that you can create your own map implementation by expanding it. When you do this, you only need to implement the selected methods, not all of them.

One use case may be a card that automatically checks all the records that you insert into it, or one that automatically updates the database when it changes.

+4
source

All Articles