14

Singleton and the DI alternative

The enum and holder singletons, and why injecting the collaborator usually beats reaching for a global.

Demo 14Source on GitHub ↗

Singleton gives exactly one instance, but a global one is a hidden dependency that fights testing. This module shows the modern Java forms, the enum singleton (serialization- and reflection-safe) and the initialization-on-demand holder idiom (lazy, thread-safe by class-initialization semantics, no double-checked locking), and then makes the real argument: prefer dependency injection, where the same capability arrives through a constructor a composition root controls.

The JUnit 5 tests prove the enum and holder each yield one instance (including a reflection test of the enum’s safety and a multi-thread race on the holder), and a Mockito-backed test shows the injected service is substitutable where a global would not be.

Build, run, observe

cd examples/14-singleton
mvn -q test
./demo.sh

The module also runs from the aggregator root with mvn -q -f examples/pom.xml test.