What is Factory Method Pattern?
The Factory Method Pattern is a creational design pattern that creates objects without exposing the creation logic to the client.
Instead of using new, object creation is handled by a factory.
Why Use Factory Method?
- Hide object creation logic
- Reduce tight coupling
- Make code flexible and scalable
- Easily add new types without modifying existing code
Real-Time Scenario
In a system:
- Payment types → UPI, Card, NetBanking
- Reports → PDF, Excel
👉 Instead of:
if(type == "UPI") new UpiPayment();
We use a factory.
Implementation
Step 1: Product Interface
public interface IPayment
{
void Pay(decimal amount);
}
Step 2: Concrete Implementations
public class UpiPayment : IPayment
{
public void Pay(decimal amount)
{
Console.WriteLine($"Paid {amount} via UPI");
}
}
public class CardPayment : IPayment
{
public void Pay(decimal amount)
{
Console.WriteLine($"Paid {amount} via Card");
}
}
Step 3: Factory Class
public class PaymentFactory
{
public static IPayment Create(string type)
{
return type switch
{
"UPI" => new UpiPayment(),
"CARD" => new CardPayment(),
_ => throw new Exception("Invalid payment type")
};
}
}
Usage Example
var payment = PaymentFactory.Create("UPI");
payment.Pay(1000);
Output
Paid 1000 via UPI
Key Concept
Instead of:
var payment = new UpiPayment();
We do:
var payment = PaymentFactory.Create("UPI");
👉 Creation logic is hidden
Advantages
- Centralized object creation
- Easy to extend (add new types)
- Reduces dependency on concrete classes
- Improves maintainability
Disadvantages
- Adds extra class (factory)
- Can become complex if too many types
- May require updates in factory when adding new types
When to Use
- When object creation logic is complex
- When you need multiple variations of objects
- When you want to decouple client from implementation
- When object type is decided at runtime
Real Project Mapping (.NET + Angular)
| Feature | Usage |
|---|---|
| Payment gateway selection | Factory |
| Report generation | Factory |
| Notification providers | Factory |
| Strategy selection | Factory |
Pro Tip (Advanced .NET Usage)
- Combine Factory + Strategy Pattern
- Use DI instead of static factory for scalability
- Use reflection or configuration-based factories for dynamic loading
Summary
Factory Method Pattern helps you:
- Hide object creation logic
- Build flexible and scalable systems
- Easily support new object types
👉 Perfect for payments, reports, providers, dynamic object creation
Comments
Post a Comment