Creational Design Pattern (C# / .NET)
Creational Design Pattern (C# / .NET)
Definition
- Focuses on how objects are created
- Hides object creation logic instead of using
newdirectly - Provides flexible and reusable object creation
Types of Creational Patterns
1. Singleton
- Only one instance exists in entire app
- Example: Logging, Configuration
2. Factory Method
- Creates objects without exposing creation logic
- Example: Payment types, Report generation
3. Abstract Factory
- Creates families of related objects
- Example: UI themes (Dark theme → buttons, inputs, etc.)
4. Builder
- Builds complex objects step by step
- Example: Invoice with multiple fields
5. Prototype
- Creates object by cloning existing object
- Example: Copy invoice template
Pros
- Loose coupling (no direct
new) - Better code reuse
- Flexible object creation
- Easier testing
- Scalable architecture
Cons
- More classes → complexity
- Harder to understand initially
- Overkill for small/simple apps
- Debugging can be indirect
When to Use (Scenarios)
- When object creation is complex
- When you need different variations of objects
- When you want to decouple creation from usage
- When object creation logic may change frequently
Real-Time Use Cases (.NET Projects)
| Scenario | Pattern |
|---|---|
| Logging service | Singleton |
| Payment methods (UPI, Card) | Factory |
| UI themes (Light/Dark) | Abstract Factory |
| Invoice creation | Builder |
| Clone existing data | Prototype |
Real-Time Coding Example (Factory Pattern)
Example: Payment system in your app
Step 1: Interface
public interface IPayment
{
void Pay(decimal amount);
}
Step 2: Implementations
public class UpiPayment : IPayment
{
public void Pay(decimal amount)
{
Console.WriteLine($"Paid {amount} using UPI");
}
}
public class CardPayment : IPayment
{
public void Pay(decimal amount)
{
Console.WriteLine($"Paid {amount} using Card");
}
}
Step 3: Factory
public class PaymentFactory
{
public static IPayment Create(string type)
{
return type switch
{
"UPI" => new UpiPayment(),
"CARD" => new CardPayment(),
_ => throw new Exception("Invalid payment type")
};
}
}
Step 4: Usage
var payment = PaymentFactory.Create("UPI");
payment.Pay(1000);
Real-Time Coding Example (Singleton in .NET Core)
builder.Services.AddSingleton<ILogService, LogService>();
public class LogService : ILogService
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
👉 Same instance used across entire application
Simple Understanding
- Without pattern →
neweverywhere ❌ - With pattern → controlled creation ✔
Comments
Post a Comment