0
0
LLDsystem_design~3 mins

Why Factory Method pattern in LLD? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could add new object types without rewriting your entire codebase?

The Scenario

Imagine you are building a software system that needs to create different types of objects, like various shapes or documents, by hand. Every time you want a new type, you write new code everywhere to create it.

The Problem

This manual approach is slow and confusing. You have to change many places in your code to add a new object type. It's easy to make mistakes and hard to keep track of all the creation logic scattered around.

The Solution

The Factory Method pattern solves this by centralizing object creation. It lets you define a method that creates objects, but lets subclasses decide which object to create. This keeps your code clean, flexible, and easy to extend.

Before vs After
Before
if(type == 'circle') { return new Circle(); } else if(type == 'square') { return new Square(); }
After
Shape shape = shapeFactory.createShape();
What It Enables

It enables easy addition of new object types without changing existing code, making your system scalable and maintainable.

Real Life Example

Think of a document editor that can create different document types like Word, PDF, or Excel. Using Factory Method, adding a new document type is simple and doesn't break existing code.

Key Takeaways

Manual object creation scatters code and causes errors.

Factory Method centralizes and delegates creation to subclasses.

This pattern makes adding new types easy and safe.