0
0
LLDsystem_design~15 mins

Factory Method pattern in LLD - Deep Dive

Choose your learning style9 modes available
Overview - Factory Method pattern
What is it?
The Factory Method pattern is a way to create objects without specifying the exact class of the object to create. Instead, it uses a method that returns an object of a common interface or base class. This lets the code decide which specific object to make at runtime. It helps keep code flexible and easy to change.
Why it matters
Without the Factory Method pattern, code would need to know the exact classes to create, making it hard to add new types or change behavior. This pattern solves the problem of tight coupling between object creation and usage. It allows systems to grow and adapt without rewriting large parts of the code, saving time and reducing bugs.
Where it fits
Before learning this, you should understand basic object-oriented programming concepts like classes, interfaces, and inheritance. After this, you can explore other design patterns like Abstract Factory, Builder, or Dependency Injection that build on or complement Factory Method.
Mental Model
Core Idea
Factory Method lets a class defer the decision of which object to create to its subclasses, promoting flexibility and reuse.
Think of it like...
Imagine a pizza shop where the main shop doesn’t bake pizzas itself but has different chefs for each pizza type. The shop just asks the right chef to make the pizza, without knowing the details of how it’s made.
┌───────────────┐       create()       ┌───────────────┐
│   Creator     │────────────────────▶│ Product       │
│ (abstract)    │                     │ (interface)   │
│ + factoryMethod()│                   │               │
└──────┬────────┘                     └───────────────┘
       │
       │ subclass implements
       ▼
┌───────────────┐
│ ConcreteCreator│
│ + factoryMethod()│
│ returns ConcreteProduct │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding Object Creation Basics
🤔
Concept: Learn how objects are normally created using constructors and why direct creation can cause tight coupling.
In simple programs, you create objects by calling their constructors directly, like new Car(). This means your code must know about the Car class exactly. If you want to change the type of car or add new car types, you must change the code everywhere you create cars.
Result
You see that direct object creation ties your code to specific classes, making it hard to change or extend.
Understanding that direct object creation causes tight coupling helps see why a pattern like Factory Method is needed.
2
FoundationIntroducing Interfaces for Flexibility
🤔
Concept: Use interfaces or base classes so code can work with any object that follows the same contract.
Instead of creating a Car directly, your code works with a Vehicle interface. Different classes like Car, Bike, or Truck implement Vehicle. Your code only knows about Vehicle, not the exact type. This allows swapping implementations without changing the code that uses them.
Result
Your code becomes more flexible and easier to extend with new vehicle types.
Knowing that programming to interfaces reduces dependency on concrete classes sets the stage for Factory Method.
3
IntermediateDefining the Factory Method
🤔Before reading on: do you think the factory method creates objects directly or just defines how to create them? Commit to your answer.
Concept: The Factory Method is an abstract method that subclasses override to create specific objects.
The Creator class declares a factoryMethod() that returns a Product interface. Subclasses override factoryMethod() to return different concrete products. The Creator uses factoryMethod() to get objects without knowing their exact class.
Result
You get a flexible way to create objects where the exact type is decided by subclasses.
Understanding that the factory method defers object creation to subclasses is key to flexible and reusable code.
4
IntermediateSeparating Object Creation from Usage
🤔Before reading on: do you think the client code should call the factory method directly or use the Creator class? Commit to your answer.
Concept: Clients use the Creator class which internally calls the factory method, hiding object creation details.
The client calls a method on Creator that uses factoryMethod() to get a Product. The client never calls new directly. This separation means clients don’t need to change when new product types are added.
Result
Clients remain unaware of concrete classes, improving code maintainability.
Knowing that hiding creation details from clients reduces code changes when extending the system is a powerful design benefit.
5
IntermediateUsing Factory Method in Real Scenarios
🤔Before reading on: do you think Factory Method is only useful for simple object creation or also for complex product families? Commit to your answer.
Concept: Factory Method can be used to create complex objects or families of related objects by subclassing creators.
For example, a document editor might have different creators for different document types (text, spreadsheet). Each creator knows how to make the right document parts. This keeps the editor code clean and extensible.
Result
You see Factory Method helps manage complexity by localizing object creation logic.
Understanding that Factory Method scales from simple to complex object creation helps apply it in real systems.
6
AdvancedExtending Factory Method with Hooks and Parameters
🤔Before reading on: do you think factory methods can accept parameters to customize created objects? Commit to your answer.
Concept: Factory methods can take parameters or use hooks to customize object creation dynamically.
Sometimes the factory method accepts arguments to decide which concrete product to create or how to configure it. Hooks are optional methods subclasses can override to adjust creation steps without changing the whole method.
Result
You gain more control and flexibility over object creation without breaking the pattern.
Knowing how to extend factory methods with parameters and hooks allows adapting the pattern to complex needs.
7
ExpertFactory Method vs Abstract Factory and Dependency Injection
🤔Before reading on: do you think Factory Method and Abstract Factory are the same or different? Commit to your answer.
Concept: Factory Method creates one product via subclassing; Abstract Factory creates families of products; Dependency Injection passes created objects from outside.
Factory Method uses inheritance to decide which object to create. Abstract Factory groups related factories to create families of products. Dependency Injection moves object creation outside the class entirely, often using containers. Each has tradeoffs in flexibility and complexity.
Result
You understand when to choose Factory Method over other creational patterns.
Understanding the subtle differences and tradeoffs between these patterns helps design scalable and maintainable systems.
Under the Hood
At runtime, the Creator class calls its factoryMethod(), which is overridden by subclasses to instantiate specific concrete products. This uses polymorphism: the call to factoryMethod() resolves to the subclass version, creating the right object without the Creator knowing its exact type. This defers object creation decisions to subclasses, enabling flexible and extensible code.
Why designed this way?
Factory Method was designed to solve the problem of tight coupling between object creation and usage. By deferring creation to subclasses, it allows new product types to be added without changing existing code. This design follows the Open/Closed Principle, promoting code that is open for extension but closed for modification.
┌───────────────┐
│   Client      │
└──────┬────────┘
       │ calls operation()
       ▼
┌───────────────┐
│   Creator     │
│ + operation() │
│ + factoryMethod() (abstract) │
└──────┬────────┘
       │ overridden by subclass
       ▼
┌───────────────┐
│ConcreteCreator│
│ + factoryMethod() returns ConcreteProduct │
└──────┬────────┘
       │ creates
       ▼
┌───────────────┐
│ConcreteProduct│
│ implements Product │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does Factory Method always create new objects or can it return existing ones? Commit to your answer.
Common Belief:Factory Method always creates a new object every time it is called.
Tap to reveal reality
Reality:Factory Method can return existing objects or cached instances if needed; it is about the interface for creation, not the creation itself.
Why it matters:Assuming it always creates new objects can lead to inefficient designs or missed opportunities for optimization like object reuse.
Quick: Is Factory Method the same as Abstract Factory? Commit to yes or no.
Common Belief:Factory Method and Abstract Factory are the same pattern with different names.
Tap to reveal reality
Reality:Factory Method creates one product via subclassing; Abstract Factory creates families of related products via object composition.
Why it matters:Confusing these patterns can lead to wrong implementations and design complexity.
Quick: Does Factory Method remove the need for constructors? Commit to your answer.
Common Belief:Factory Method replaces constructors entirely.
Tap to reveal reality
Reality:Factory Method uses constructors internally but hides them behind a method to control object creation.
Why it matters:Misunderstanding this can cause confusion about object lifecycle and initialization.
Quick: Can Factory Method be used without inheritance? Commit to yes or no.
Common Belief:Factory Method can be implemented without subclassing.
Tap to reveal reality
Reality:Factory Method relies on subclassing to override the creation method; without inheritance, it is not Factory Method.
Why it matters:Trying to implement Factory Method without inheritance misses the pattern’s core benefit of deferred creation.
Expert Zone
1
Factory Method can be combined with Template Method pattern where the factory method is a step in a larger algorithm.
2
Subclasses can override factory methods to return different product variants dynamically based on runtime conditions.
3
Factory Method supports lazy initialization by creating objects only when needed, improving performance.
When NOT to use
Avoid Factory Method when you need to create families of related objects together; Abstract Factory is better then. Also, if you want to inject dependencies from outside, Dependency Injection frameworks are more suitable.
Production Patterns
In real systems, Factory Method is used in frameworks to allow users to extend behavior by subclassing. For example, GUI toolkits use it to create widgets, or document editors use it to create document parts. It helps keep core code stable while allowing customization.
Connections
Abstract Factory pattern
Builds-on
Understanding Factory Method helps grasp Abstract Factory, which groups multiple factory methods to create related objects.
Dependency Injection
Alternative approach
Knowing Factory Method clarifies how Dependency Injection differs by moving object creation outside classes entirely.
Biological cell differentiation
Similar pattern
Just like stem cells differentiate into specific cell types based on signals, Factory Method defers object creation to subclasses deciding the final type.
Common Pitfalls
#1Creating objects directly in client code instead of using the factory method.
Wrong approach:Car car = new SportsCar(); // client creates object directly
Correct approach:Car car = carFactory.createCar(); // client uses factory method
Root cause:Not understanding that Factory Method centralizes creation to reduce coupling.
#2Making the factory method static, preventing subclass overrides.
Wrong approach:static Car createCar() { return new SportsCar(); }
Correct approach:Car createCar() { return new SportsCar(); } // instance method overridden by subclass
Root cause:Misunderstanding that Factory Method relies on polymorphism via subclassing.
#3Putting complex business logic inside the factory method.
Wrong approach:Car createCar() { if(condition) { doComplexLogic(); } return new SportsCar(); }
Correct approach:Car createCar() { return new SportsCar(); } // keep factory method simple; complex logic elsewhere
Root cause:Confusing object creation responsibility with business logic.
Key Takeaways
Factory Method pattern defers object creation to subclasses, promoting flexible and reusable code.
It separates the code that uses objects from the code that creates them, reducing tight coupling.
Factory Method relies on polymorphism and inheritance to decide which object to create at runtime.
It is different from but related to Abstract Factory and Dependency Injection patterns.
Understanding Factory Method helps design systems that are easier to extend and maintain.