Implement Registry in Java as a focused lookup boundary rather than a hidden global dependency mechanism.
Registry: A component that maps keys to objects, factories, or handlers and provides controlled lookup for those entries.
Registry is useful when callers need to choose behavior by key, type, or identifier without hard-coding every mapping. That often appears in plugin systems, serializer dispatch, message handlers, or export format selection.
1public final class FormatterRegistry {
2 private final Map<String, Formatter> formatters;
3
4 public FormatterRegistry(Map<String, Formatter> formatters) {
5 this.formatters = Map.copyOf(formatters);
6 }
7
8 public Formatter formatterFor(String key) {
9 Formatter formatter = formatters.get(key);
10 if (formatter == null) {
11 throw new IllegalArgumentException("Unknown formatter: " + key);
12 }
13 return formatter;
14 }
15}
This is a healthy registry because:
Registry starts drifting into trouble when:
At that point, it begins to look more like service locator than focused registry.
When reviewing a registry, ask:
A good registry is a disciplined index. A bad one is an unbounded dependency warehouse.