The 23 foundational GoF patterns help structure code in services and modules to achieve maintainability, flexibility, and robust coupling control.
1. Creational Patterns
Mechanisms to create objects, increasing flexibility and reusability while hiding complex instantiation.
| Pattern | Purpose | When to Apply | Example |
|---|---|---|---|
| Factory Method | Define an interface for creating an object; subclasses decide which class to instantiate. | When the class cannot anticipate the type to create. | `ILoggerFactory` returning `FileLogger` or `DbLogger`. |
| Abstract Factory | Create families of related objects without specifying concrete classes. | Configure system with one of multiple product families. | DB pool producing `Connection`, `Command`, `Transaction` for Oracle/MySQL. |
| Builder | Separate construction of a complex object from its representation. | When an object has many parameters; constructors would be complex. | `HttpClient.Builder` building config step-by-step. |
| Singleton | Ensure a single instance and a global access point. | Exactly one instance coordinates actions; global resource. | Global configuration manager; centralized connection pool. |
| Prototype | Create new objects by copying an existing prototype. | Object creation is expensive or to avoid coupling to creation. | Cloning complex configuration state quickly. |
2. Structural Patterns
Composition of classes/objects to form larger, flexible structures.
| Pattern | Purpose | When to Apply | Example |
|---|---|---|---|
| Adapter | Convert one interface to another expected by clients. | Integrate legacy components with new interfaces. | Use JSON logger with a system expecting XML logger. |
| Decorator | Dynamically add responsibilities to an object. | Add behaviors without changing class structure. | Wrap file stream with encryption, compression, buffering. |
| Facade | Provide a unified high-level interface to a subsystem. | Simplify and decouple client code from subsystem. | `BillingServiceFacade` coordinating Payment, Tax, Inventory. |
| Composite | Compose objects into trees to represent part-whole hierarchies. | File system or org chart trees; uniform treatment. | UI component trees: container vs single element. |
| Bridge | Decouple abstraction from implementation so both can vary. | Abstraction/implementation should not be tightly bound. | Decouple `Reporting` from `PostgresImpl`/`MySQLImpl` drivers. |
| Flyweight | Share intrinsic state to support large numbers of fine-grained objects efficiently. | When many similar objects exist and memory usage is critical. | Character glyphs in a text editor sharing shapes and fonts. |
| Proxy | Provide a surrogate or placeholder to control access to another object. | Lazy-loading, remote access, access control, or caching. | Virtual proxy for images; remote proxy for network services. |
3. Behavioral Patterns
Improve communication between objects; manage algorithms, control flow, and responsibilities.
| Pattern | Purpose | When to Apply | Example |
|---|---|---|---|
| Observer | One-to-many dependency; observers update when subject changes. | Notify many objects without tight coupling. | Service event bus: `UserStateChanged` notifies `CacheUpdater`, `Logger`. |
| Strategy | Encapsulate interchangeable algorithms. | Related classes differ only by behavior. | Checkout pricing strategies: `StandardPricing`, `LoyaltyDiscountStrategy`. |
| Command | Encapsulate requests; support parameterization, queuing, logging, undo. | Undo/redo; async job scheduling. | Job scheduler with `Command` objects for deferred execution. |
| Iterator | Sequential access to aggregate elements without exposing representation. | Abstract over complex data structures. | Standard iteration for lists, maps, trees. |
| State | Alter object behavior when internal state changes. | Implement complex state machines. | Order Status transitions: Pending → Paid → Shipped. |
| Chain of Responsibility | Pass requests along a chain until a handler processes it. | When multiple handlers may process a request without coupling to sender. | HTTP middleware pipeline; validation chains. |
| Interpreter | Define a grammar and interpret sentences in that language. | When simple domain-specific languages are needed. | Expression evaluators; rule engines for filters. |
| Mediator | Encapsulate object interactions to reduce direct dependencies. | Complex communication patterns among many objects. | UI dialog coordinating controls; message brokers. |
| Memento | Capture and externalize an object’s internal state for restoration. | Implement undo/rollback without exposing internals. | Editor undo stack storing snapshots. |
| Template Method | Define the skeleton of an algorithm; let subclasses override steps. | Shared workflow with variant steps. | Report generation pipeline with overridable rendering steps. |
| Visitor | Separate algorithms from object structures; add operations without changing classes. | Operate across complex object hierarchies. | AST traversals; applying operations over composite structures. |
Pattern Families Coverage
Count of patterns per family (Creational: 5, Structural: 7, Behavioral: 11).