Implement Extension Object in Java by exposing optional capabilities through explicit extension lookup rather than bloating the primary type.
Extension Object: A pattern where an object can expose optional capabilities through separate extension types rather than encoding all features in its primary interface.
A simple Java shape looks like this:
1public interface Extensible {
2 <T> Optional<T> extension(Class<T> type);
3}
An implementation can keep a registry of supported extensions:
1public final class Document implements Extensible {
2 private final Map<Class<?>, Object> extensions = new HashMap<>();
3
4 public <T> void register(Class<T> type, T extension) {
5 extensions.put(type, extension);
6 }
7
8 @Override
9 public <T> Optional<T> extension(Class<T> type) {
10 return Optional.ofNullable(type.cast(extensions.get(type)));
11 }
12}
The base object stays small, while optional capabilities can be discovered explicitly.
Use this pattern when capability variation is real and the base type would otherwise become overloaded with optional methods.