
When you start coding, creating objects is simple:
Product product = new Product();
But as your application grows, object creation often becomes… messy.
- Different variants of the same object
- Complex initialization logic
- Conditional creation based on input
At some point, new stops being enough.
That’s where the Factory pattern comes in.
The Problem: Scattered Object Creation
Let’s say you’re building a payment system:
public interface Payment {
void process();
}
public class CreditCardPayment implements Payment {
@Override
public void process() {
System.out.println(“Processing credit card payment”);
}
}
public class PayPalPayment implements Payment {
@Override
public void process() {
System.out.println(“Processing PayPal payment”);
}
}
Now imagine using it:
Payment payment;
if (type.equals(“card”)) {
payment = new CreditCardPayment();
} else if (type.equals(“paypal”)) {
payment = new PayPalPayment();
} else {
throw new IllegalArgumentException(“Unknown payment type”);
}
Problems that occurs:
- Logic spread across the codebase
- Hard to extend (add a new payment = update everywhere)
- Violates Open/Closed Principle
The Solution: Factory
Encapsulate object creation in one place.
Factory Class Example:
public class PaymentFactory {
public static Payment createPayment(String type) {
switch (type.toLowerCase()) {
case “card”:
return new CreditCardPayment();
case “paypal”:
return new PayPalPayment();
default:
throw new IllegalArgumentException(“Unknown payment type”);
}
}
}
Usage Example would be:
Payment payment = PaymentFactory.createPayment("paypal");
payment.process();
Benefits of this approach:
- Centralized creation
- Cleaner business logic
- Easier to extend
When Should You Use Factory?
Factory is a great fit when:
- You have multiple implementations of an interface
- Creation logic depends on conditions or configuration
- You want to hide implementation details
- You need to decouple usage from instantiation
When avoiding Factories?
Avoid Factory when:
- You create simple objects
- There’s no variation in implementations
- You don’t need abstraction

No responses yet