Cheatsheet
Singleton
Intent
Make sure a class has exactly one instance, and that everyone who needs it uses that same one through a well-known access point.
Structure (UML)
classDiagram
direction LR
class WodController {
<<Client>>
+list() List~Wod~
+add(Wod wod) Wod
}
class BookingService {
<<Client>>
+book(String wod) Booking
}
class WodCatalog {
<<Singleton>>
-Map~String, Wod~ wods
+find(String name) Optional~Wod~
+all() List~Wod~
+add(Wod wod) void
}
WodController --> WodCatalog
BookingService --> WodCatalogParticipants
- Singleton (WodCatalog), the class that should only exist once
- Access point, getInstance() in the GoF version and bean injection in Spring
- Clients (WodController, BookingService), which use the shared instance without creating it
WodCatalog.java
@Component
public class WodCatalog {
private final Map<String, Wod> wods = new ConcurrentHashMap<>();
public WodCatalog() {
wods.put("Fran", new Wod("Fran", "21-15-9 thrusters and pull-ups"));
wods.put("Cindy", new Wod("Cindy", "20-minute AMRAP: 5 pull-ups, 10 push-ups, 15 air squats"));
}
public Optional<Wod> find(String name) {
return Optional.ofNullable(wods.get(name));
}
// …
}Pros
- One source of truth, because everybody sees the same data
- The expensive work (loading the catalog) happens once
- With Spring you write none of the pattern, and you can still swap the bean in tests
Cons
- Shared state is used by many threads at once, so it has to be safe
- In its classic form it's a global in disguise, coupling code and polluting tests
- Easy to abuse by putting per-request state in a singleton