Design Patterns in Java
Prerequisites: Pattern matching
A few patterns that show up constantly in real Java codebases:
Singleton — exactly one instance of a class, accessed globally:
class AppConfig {
private static final AppConfig INSTANCE = new AppConfig();
private AppConfig() {}
static AppConfig getInstance() { return INSTANCE; }
}
Factory — a method that decides which concrete class to instantiate, hiding the decision from the caller:
static Shape createShape(String kind) {
return switch (kind) {
case "circle" -> new Circle(1.0);
case "square" -> new Square(1.0);
default -> throw new IllegalArgumentException("Unknown shape: " + kind);
};
}
Strategy — swap an algorithm's behavior via an interface,
without an if/else chain at the call site (this is exactly what a
Comparator passed to .sort() already does).
Common mistakes
- Reaching for a pattern because it's a "known pattern," not because it solves an actual problem in front of you — an unneeded Singleton or Factory just adds indirection.