What if you could add new object types without rewriting your entire codebase?
Why Factory Method pattern in LLD? - Purpose & Use Cases
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.
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 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.
if(type == 'circle') { return new Circle(); } else if(type == 'square') { return new Square(); }
Shape shape = shapeFactory.createShape();
It enables easy addition of new object types without changing existing code, making your system scalable and maintainable.
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.
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.