Design Patterns โ Creational Patterns
Master the five Creational Design Patterns from the Gang of Four โ Singleton, Factory Method, Abstract Factory, Builder, and Prototype โ with real-world examples.
โDesign Patterns are reusable solutions to commonly occurring problems in software design. The term was popularized by four authors โ Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides โ known as the Gang of Four, or GoF. Their 1994 book defined 23 patterns organized into three categories. Creational patterns control how objects are created. Structural patterns define how classes and objects are composed into larger structures. Behavioral patterns define communication and responsibility between objects. Patterns are not code you copy and paste โ they're templates, conceptual solutions that you adapt to your specific context. Using patterns gives your team a shared vocabulary: when you say 'we'll use a Factory for this,' every experienced developer immediately understands the structure. Patterns represent proven solutions refined over decades of real-world engineering. But beware anti-patterns: applying a pattern where it doesn't fit โ adding complexity without solving a real problem โ is worse than no pattern at all.โ
โThe Singleton pattern ensures a class has exactly one instance throughout the application's lifetime, and provides a global access point to that instance. Classic use cases: a database connection pool, a logging service, an application configuration manager, a thread pool. You want exactly one pool โ not one per class that needs it. Implementation: make the constructor private so no external code can call new. Provide a static getInstance() method that creates the instance on first call and returns the existing instance on subsequent calls. Thread safety is critical: in a multi-threaded environment, two threads could simultaneously enter getInstance() and both create an instance. Use double-checked locking or the initialization-on-demand holder pattern. The modern criticism of Singleton: it's essentially global state. Global state makes unit testing difficult because you can't control what getInstance() returns in a test. The modern preference: use a dependency injection container configured to return a singleton-scoped instance. You get the same behavior without the testing problem.โ
โThe Factory Method pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. The 'factory' is a method โ either abstract in a base class or defined in an interface โ that subclasses override to produce specific types. The practical example: a notification system. You have a Notifier base class with an abstract createNotification() factory method. EmailNotifier overrides it to return an EmailNotification. SMSNotifier overrides it to return an SMSNotification. PushNotifier returns a PushNotification. The client code that sends notifications doesn't know or care which concrete type it's working with โ it just calls send() on whatever the factory method returned. The power is in extension: when you add WhatsAppNotification, you add one new class and one new factory subclass. Zero changes to existing code โ this is the Open/Closed Principle in action. Factory Method is everywhere in Java: Collection.iterator() returns different iterator implementations depending on the collection type. JDBC's DriverManager.getConnection() returns different database drivers.โ
โThe Builder pattern addresses a specific, painful problem: constructors with too many parameters. When a class has 10 or 15 configuration options, a constructor becomes unreadable. Which positional argument was the timeout? Was the second boolean the SSL flag or the retry flag? The Builder pattern provides a fluent interface: a chain of method calls, each setting one property by name, concluded by a build() call that creates the final, often immutable, object. Example: HttpRequest.builder().url('https://api.example.com').method('POST').header('Content-Type', 'application/json').timeout(Duration.ofSeconds(30)).build(). Every parameter is named. You set only the parameters you care about. And the resulting HttpRequest is immutable โ once built, it can't be accidentally modified. The pattern is everywhere: Java's StringBuilder is a simplified builder. Lombok's @Builder annotation generates a full builder automatically. SQL query builders like Hibernate's Criteria API use the pattern. Android's AlertDialog.Builder is the classic mobile example.โ
โPrototype creates new objects by cloning an existing prototype instance instead of creating from scratch. The use case: object creation is expensive โ it involves a database query, an API call, or complex computation. Create one instance with all that expense, then clone it whenever you need another. The clone() method must handle deep vs shallow copy: a shallow copy shares nested object references while a deep copy creates independent copies of everything. For most use cases, deep copy is safer. Abstract Factory is a step above Factory Method: it creates entire families of related objects. The classic example: a UI toolkit with a DarkThemeFactory and a LightThemeFactory. DarkThemeFactory creates DarkButton, DarkDialog, and DarkInput. LightThemeFactory creates LightButton, LightDialog, and LightInput. The UI code that builds your application depends only on the AbstractFactory interface โ it calls createButton(), createDialog(), createInput(). To switch from dark to light theme, you swap the factory. Zero changes to the UI rendering code. Abstract Factory is the natural extension when your application needs multiple coordinated families of objects.โ
โHere's your decision guide for Creational Patterns. Singleton: when you genuinely need exactly one instance โ a resource pool, a cache, a central config. Prefer dependency injection containers to manage the singleton lifecycle over hand-rolled static instances. Factory Method: when you want to decouple the code that uses an object from the code that creates it, and when you need to support adding new types without modifying existing code. Abstract Factory: when you need to create entire families of related objects that must work together, and you want to be able to swap out the entire family. Builder: whenever a constructor would need more than three or four parameters, especially when many are optional. Prototype: when object creation is expensive and you have an existing instance that can serve as a template for new instances. Creational patterns are the foundation โ they control how your system's objects come into existence, which affects every other aspect of the design.โ
- 1Implement a thread-safe Singleton for a database connection pool
- 2Build a Factory Method for creating different notification types (Email, SMS, Push)
- 3Design a Builder pattern for constructing complex HTTP request objects
- 4Implement Prototype for cloning configuration objects