17.1 Design Patterns Overview
Design patterns are proven solutions to recurring problems in software development. Like architectural blueprints, they provide reusable code structures and design ideas for similar situations.
The 23 patterns cataloged by the Gang of Four (GoF) in their 1994 book "Design Patterns: Elements of Reusable Object-Oriented Software" are the industry standard, organized into three categories.
1. Why Learn Design Patterns?
- Common vocabulary: "Let's use the Singleton pattern here" quickly communicates intent to teammates.
- Proven solutions: Avoid solving from scratch problems that countless developers have already solved.
- Maintainability: Code following patterns is resilient to change and extension.
- Job interviews: Design patterns are a staple topic in backend developer interviews.
2. Three Categories
| Category | Purpose | Key Patterns |
|---|---|---|
| Creational | Encapsulate object creation | Singleton, Factory Method, Builder, Prototype, Abstract Factory |
| Structural | Compose classes/objects into larger structures | Adapter, Decorator, Proxy, Facade, Composite |
| Behavioral | Distribute responsibility and collaboration between objects | Strategy, Observer, Template Method, Command, Iterator |
3. Design Patterns in the Java Standard Library
| Pattern | Java Standard Library Example |
|---|---|
| Singleton | Runtime.getRuntime(), System |
| Factory Method | Calendar.getInstance(), List.of() |
| Builder | StringBuilder, Stream.Builder |
| Iterator | Iterator<E>, for-each loop |
| Observer | EventListener |
| Strategy | Comparator<T>, Runnable |
| Decorator | BufferedReader, Collections.unmodifiableList() |
| Proxy | java.lang.reflect.Proxy |
| Adapter | Arrays.asList(), InputStreamReader |