Factory Method Pattern


🔹 Introduction
Creating objects in Java is easy—just use the new
keyword, right?
But what happens when your code needs to create different types of objects based on user input, configurations, or conditions? Things get messy fast.
That’s where the Factory Method Pattern steps in.
It provides a clean way to delegate object creation to a separate class, so your core logic doesn't have to worry about what is being created — it just asks the factory to “make the right thing.”
🏪 Real-World Analogy
Imagine an online food delivery app.
You place an order, but you don’t care which restaurant prepares your food — you just want your pizza, your burger, or your biryani. 🍕🍔🍛
The app acts like a factory, choosing the right restaurant (object) for your order (need), based on criteria like cuisine or location.
You get what you want without knowing how or where it was created. That’s the Factory Method Pattern in action.
“One factory. Multiple outputs. Factory Method Pattern in Java explained.”
🧰 The Problem It Solves
In object-oriented programming, we often rely on the new
keyword to create objects:
Shape shape = new Circle();
But what if you don’t know which subclass you’ll need until runtime?
Worse, what if your object creation logic is scattered all over your codebase?
This tight coupling to concrete classes makes your code:
Harder to extend (adding new types means changing existing logic)
Harder to test (direct instantiation is tough to mock)
Harder to maintain (adding/removing types requires search-and-replace chaos)
🚫 Without Factory Method
if(type.equals("circle")) {
return new Circle();
} else if(type.equals("square")) {
return new Square();
}
This logic is rigid. Adding a Triangle
? You have to modify the code — again.
✅ With Factory Method
The Factory Method encapsulates the decision of which object to create inside a dedicated method.
Now your code only talks to interfaces, and lets the factory worry about instantiation.
This makes your code:
Flexible to extend
Decoupled from object creation
Compliant with SOLID principles (especially OCP — Open/Closed Principle)
🧪 Basic Java Implementation – Factory Method Pattern
Let’s walk through a simple example to understand how the Factory Method Pattern works in Java.
“How the Factory Method Pattern works in Java – one factory, many shapes!”
👨🏫 Step 1: Define a Common Interface
public interface Shape {
void draw();
}
🟢 Step 2: Create Concrete Implementations
public class Circle implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Circle");
}
}
public class Square implements Shape {
@Override
public void draw() {
System.out.println("Drawing a Square");
}
}
🏭 Step 3: Create the Factory Class
public class ShapeFactory {
public Shape getShape(String type) {
if (type == null) return null;
switch (type.toLowerCase()) {
case "circle": return new Circle();
case "square": return new Square();
default: return null;
}
}
}
🧪 Step 4: Use It in Your Application
public class Main {
public static void main(String[] args) {
ShapeFactory factory = new ShapeFactory();
Shape shape1 = factory.getShape("circle");
shape1.draw(); // Output: Drawing a Circle
Shape shape2 = factory.getShape("square");
shape2.draw(); // Output: Drawing a Square
}
}
✅ Why Do We Do It This Way?
We abstract away the creation logic — the caller doesn’t need to know which class to instantiate.
If we want to add a new
Triangle
, we don’t touch the client code — just extend the factory.Encourages programming to an interface instead of a concrete class.
Keeps our codebase extensible and maintainable.
This is the core idea behind the Factory Method. In real-world apps, you’ll often see more advanced variants with abstract factories or even dependency injection — but this is the foundation.
🍕 Real-World Analogy – Factory Method Pattern
Let’s revisit our earlier analogy — but this time, go deeper.
🛵 The Food Delivery App
Think of Swiggy, Zomato, or Uber Eats. When you place an order for a “Pizza”, the app doesn’t tell you where it’s being cooked.
Instead:
It checks your location
Matches cuisine type
Chooses the right restaurant (e.g., Pizza Palace or Cheesy Slice)
You just ask for food. The app chooses the source.
This is exactly what the Factory Method does in code!
“Ordering pizza? You just ask — the app decides. That’s the Factory Method in real life.”
🤖 In Tech Terms
You (the user) = Application/client
The app logic = Factory Method
The selected restaurant = Concrete implementation (
Circle
,Square
, etc.)
The creation logic is separated from your decision. You don’t hard-code the source — you just ask for a result.
✅ Why It Works
Scalable: New restaurants (types) can be added without changing how you order
Decoupled: The app doesn’t care who delivers — just that someone does
Flexible: Same app works across cuisines, locations, and user needs
This real-world thinking helps you apply Factory Method in any domain:
🛒 e-commerce (payment gateways),
🎮 game dev (enemy types),
🚚 logistics (transport modes), and more.
🎯 When to Use the Factory Method Pattern
You don’t always need a factory. But when you do, it really helps.
Here are scenarios where the Factory Method Pattern shines:
✅ Use It When:
🔹 Your code needs to decide which class to instantiate at runtime
e.g., loading plugins, choosing payment gateways, or switching storage providers
🔹 You want to avoid tight coupling between your code and concrete classes
This makes testing, mocking, and swapping dependencies easier
🔹 You expect the list of types to grow
e.g., new shapes, document types, transport modes
🔹 You want to adhere to the Open/Closed Principle
Add new functionality (like new object types) without touching existing code
“Dynamic decisions in code — choose at runtime what to create!”
🧩 Common Real-World Use Cases
💳 Payment Processing Systems
Choose between Stripe
, PayPal
, or Razorpay
at runtime.
📦 E-commerce Order Fulfillment
Select the right shipping provider (FedEx
, DHL
, BlueDart
) based on location.
🕹️ Game Development
Create different types of enemies or weapons based on level progression.
🧪 Data Parsers or Report Generators
Instantiate the correct parser (CSV
, JSON
, XML
) based on file type.
The Factory Method Pattern gives your app the flexibility to grow, without becoming a tangled mess.
🔚 Wrapping Up
The Factory Method Pattern is one of the simplest yet most powerful design patterns in object-oriented programming.
By delegating object creation to a factory class, you:
Reduce tight coupling
Increase flexibility and testability
Make your codebase easier to maintain and extend
From payment systems to UI components, and from file parsers to game characters — this pattern gives you a clean, reusable approach to handling object creation logic.
🙌 Enjoyed this Deep Dive?
If you found this blog helpful, feel free to share it with your peers, bookmark it for future reference, or leave a ❤️ to support the effort.
🔗 Follow my blog on Hashnode: ns717.hashnode.dev
💼 Connect with me on LinkedIn: Nitin Singh
Thanks for reading, and happy coding! 💻✨
Stay tuned as we continue building your design pattern toolkit, one pattern at a time!
Subscribe to my newsletter
Read articles from Nitin Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nitin Singh
Nitin Singh
I'm a passionate Software Engineer with over 12 years of experience working with leading MNCs and big tech companies. I specialize in Java, microservices, system design, data structures, problem solving, and distributed systems. Through this blog, I share my learnings, real-world engineering challenges, and insights into building scalable, maintainable backend systems. Whether it’s Java internals, cloud-native architecture, or system design patterns, my goal is to help engineers grow through practical, experience-backed content.