Design Patterns
Definition
Design Patterns are reusable, general solutions to commonly occurring design problems within a given context — they are not finished code, but templates/blueprints that can be adapted to solve a recurring design problem in object-oriented design.
Origin
Popularized by the "Gang of Four" (GoF) — Gamma, Helm, Johnson, Vlissides — in their 1994 book "Design Patterns: Elements of Reusable Object-Oriented Software", which cataloged 23 classic patterns.
Categories of GoF Design Patterns
1. Creational Patterns (object creation mechanisms)
- Singleton — ensures a class has only one instance, with a global access point
- Factory Method — creates objects without specifying the exact class to instantiate
- Abstract Factory — creates families of related objects
- Builder — constructs complex objects step by step
- Prototype — creates new objects by cloning an existing instance
2. Structural Patterns (composing classes/objects into larger structures)
- Adapter — allows incompatible interfaces to work together
- Decorator — adds behavior to objects dynamically without altering their class
- Facade — provides a simplified interface to a complex subsystem
- Composite — treats individual objects and compositions uniformly (tree structures)
- Proxy — provides a placeholder/surrogate to control access to another object
3. Behavioral Patterns (communication between objects)
- Observer — one-to-many dependency; when one object changes state, all dependents are notified
- Strategy — defines a family of interchangeable algorithms
- Command — encapsulates a request as an object
- Iterator — provides a way to access elements of a collection sequentially
- State — allows an object to alter its behavior when its internal state changes
Why Use Design Patterns
- Provide proven, tested solutions to recurring problems
- Improve communication among developers (shared vocabulary — "just use a Factory here")
- Promote reusability, flexibility, and maintainability
- Avoid reinventing the wheel
Benefits vs. Risks
| Benefit | Risk |
|---|---|
| Proven, well-understood solutions | Overuse can lead to unnecessary complexity |
| Common vocabulary for teams | Misapplying a pattern to the wrong problem |
| Improves flexibility/extensibility | Learning curve for beginners |
Exam tip: Memorize the 3 categories (Creational, Structural, Behavioral) and at least 2 patterns per category with a one-line description — Singleton, Observer, and Factory are the most commonly asked individual patterns.