Posts

Prototype Pattern in C# – Real-Time Example (Cloning Invoice Template)

What is Prototype Pattern? The Prototype Pattern is a creational design pattern that creates new objects by cloning an existing object instead of creating from scratch. Why Use Prototype Pattern? Avoid expensive object creation Quickly duplicate existing objects Preserve object state (template-based creation) Improve performance Real-Time Scenario In an Invoice System : You have a predefined invoice template You want to create multiple similar invoices 👉 Instead of building from scratch, you clone it Implementation Step 1: Prototype Interface (Optional) public interface IPrototype<T> { T Clone(); } Step 2: Concrete Class public class Invoice : IPrototype<Invoice> { public string Customer { get; set; } public decimal Amount { get; set; } public Invoice Clone() { return (Invoice)this.MemberwiseClone(); // shallow copy } } Usage Example // Original template var template = new Invoice { ...

Builder Pattern in C# – Real-Time Example (Invoice Creation)

What is Builder Pattern? The Builder Pattern is a creational design pattern that builds complex objects step by step . It separates object construction from its representation . Why Use Builder Pattern? Handle complex object creation Avoid constructors with too many parameters Improve readability and maintainability Create different representations of same object Real-Time Scenario In an Invoice System , an invoice may contain: Customer details Items Tax Discount Date 👉 Instead of one huge constructor, we build it step by step Implementation Step 1: Product (Invoice) public class Invoice { public string Customer { get; set; } public decimal Amount { get; set; } public decimal Tax { get; set; } public decimal Discount { get; set; } } Step 2: Builder public class InvoiceBuilder { private readonly Invoice _invoice = new(); public InvoiceBuilder SetCustomer(string customer) { _invoice.Custom...

Abstract Factory Pattern in C# – Real-Time Example (UI Theme System)

What is Abstract Factory Pattern? The Abstract Factory Pattern is a creational design pattern that creates families of related objects without specifying their concrete classes . It provides a factory of factories . Why Use Abstract Factory? Ensure related objects are used together Maintain consistency across components Avoid mixing incompatible objects Improve scalability and flexibility Real-Time Scenario In a UI system: Light Theme → Light Button, Light TextBox Dark Theme → Dark Button, Dark TextBox 👉 All components should match the selected theme Implementation Step 1: Abstract Products public interface IButton { void Render(); } public interface ITextBox { void Render(); } Step 2: Concrete Products (Light Theme) public class LightButton : IButton { public void Render() => Console.WriteLine("Light Button"); } public class LightTextBox : ITextBox { public void Render() => Console.WriteLine("L...

Factory Method Pattern in C# – Real-Time Example (Object Creation Simplified)

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.WriteLin...

Singleton Pattern in C# – Real-Time Example (Shared Instance)

What is Singleton Pattern? The Singleton Pattern is a creational design pattern that ensures only one instance of a class exists throughout the application and provides a global access point to it. Why Use Singleton? Share a single instance across the app Avoid multiple object creation Manage global resources efficiently Real-Time Scenario Logging service Configuration settings Cache service Application-wide settings Basic Implementation (Classic) public class Logger { private static Logger _instance; private Logger() { } public static Logger GetInstance() { if (_instance == null) _instance = new Logger(); return _instance; } public void Log(string message) { Console.WriteLine(message); } } Usage var logger1 = Logger.GetInstance(); var logger2 = Logger.GetInstance(); Console.WriteLine(logger1 == logger2); // True logger1.Log("Hello Singleton"); 👉 Both...

Composite Pattern in C# – Real-Time Example (Hierarchical Structures)

What is Composite Pattern? The Composite Pattern is a structural design pattern that lets you treat individual objects and groups of objects in the same way . It is mainly used for tree-like (hierarchical) structures . Why Use Composite Pattern? Handle single objects and collections uniformly Simplify complex hierarchical structures Enable recursive operations Improve scalability Real-Time Scenario Folder → contains files & subfolders Invoice → contains multiple items Product → single item or grouped items 👉 You can calculate total price the same way for both Implementation Step 1: Component Interface public interface IComponent { decimal GetPrice(); } Step 2: Leaf (Single Object) public class Product : IComponent { private readonly decimal _price; public Product(decimal price) { _price = price; } public decimal GetPrice() => _price; } Step 3: Composite (Group of Objects) public class ...

Facade Pattern in C# – Real-Time Example (Simplifying Complex Systems)

What is Facade Pattern? The Facade Pattern is a structural design pattern that provides a simple, unified interface to a complex system . It hides internal complexity and exposes only what is needed. Why Use Facade Pattern? Simplify complex workflows Reduce direct dependency on multiple classes Improve readability and usability Provide a clean API layer Real-Time Scenario In an Order System , placing an order involves: Creating order Processing payment Sending notification 👉 Instead of calling all services separately, use a facade. Implementation Step 1: Subsystems (Complex Services) public class OrderService { public void CreateOrder() => Console.WriteLine("Order Created"); } public class PaymentService { public void ProcessPayment() => Console.WriteLine("Payment Done"); } public class NotificationService { public void Send() => Console.WriteLine("Notification Sent"); } Step 2: F...

Decorator Pattern in C# – Real-Time Example (Dynamic Behavior Addition)

What is Decorator Pattern? The Decorator Pattern is a structural design pattern that adds new behavior to an object dynamically without modifying its original code . It wraps the original object and extends its functionality. Why Use Decorator Pattern? Add features without changing existing code Follow Open/Closed Principle Avoid subclass explosion Enable flexible combinations of behaviors Real-Time Scenario In an Invoice System : Base amount = 1000 Add discount Add tax Add logging 👉 Instead of modifying Invoice , we decorate it Implementation Step 1: Component Interface public interface IInvoice { decimal GetAmount(); } Step 2: Concrete Component public class Invoice : IInvoice { public decimal GetAmount() => 1000; } Step 3: Decorator (Add Behavior) public class DiscountDecorator : IInvoice { private readonly IInvoice _invoice; public DiscountDecorator(IInvoice invoice) { _invoice = invoic...

Adapter Pattern in C# – Real-Time Example (3rd-Party API Integration)

What is Adapter Pattern? The Adapter Pattern is a structural design pattern that converts one interface into another so that incompatible classes can work together. It acts as a bridge between your system and an external/legacy system . Why Use Adapter Pattern? Integrate third-party or legacy systems Avoid modifying existing code Provide a consistent interface to clients Improve reusability Real-Time Scenario You have your system expecting: IPayment.Pay() But a third-party service provides: MakePayment() 👉 Interfaces don’t match → Adapter solves this Implementation Step 1: Target Interface (Your System) public interface IPayment { void Pay(); } Step 2: Third-Party Service (Incompatible) public class ThirdPartyPayment { public void MakePayment() { Console.WriteLine("Paid via third-party"); } } Step 3: Adapter (Bridge) public class PaymentAdapter : IPayment { private readonly ThirdPartyPayme...

Mediator Pattern in C# – Real-Time Example (Centralized Communication)

What is Mediator Pattern? The Mediator Pattern is a behavioral design pattern where a central object controls communication between multiple objects . Instead of objects talking to each other directly, they communicate through a mediator. Why Use Mediator Pattern? Avoid complex object-to-object dependencies Centralize communication logic Improve maintainability and scalability Reduce tight coupling Real-Time Scenario Chat system (users send messages via server) Multiple services interacting in backend Form components interacting in UI Microservices coordination Basic Implementation Mediator public class Mediator { public void Send(string message, User user) { Console.WriteLine($"{user.Name}: {message}"); } } Colleague (User) public class User { private readonly Mediator _mediator; public string Name { get; } public User(Mediator mediator, string name) { _mediator = mediator; ...

Command Pattern in C# – Real-Time Example (Action Handling in Applications)

What is Command Pattern? The Command Pattern is a behavioral design pattern that encapsulates a request as an object , allowing you to parameterize, queue, or log operations. Instead of calling methods directly, you wrap them inside command objects. Why Use Command Pattern? Decouple sender (UI/API) from receiver (business logic) Enable undo/redo operations Support logging, queuing, and auditing Make code extensible and maintainable Real-Time Scenario In an application: Button click → Save / Delete / Update API request → Create / Update / Cancel Invoice Instead of directly calling service methods, we use commands. Implementation Step 1: Command Interface public interface ICommand { void Execute(); } Step 2: Concrete Command public class CreateInvoiceCommand : ICommand { public void Execute() { Console.WriteLine("Invoice Created"); } } Step 3: Usage ICommand command = new CreateInvoiceCommand(); ...

Observer Pattern in C# – Real-Time Example (Order Notification System)

What is Observer Pattern? The Observer Pattern is a behavioral design pattern where one object (subject) notifies multiple objects (observers) when a change occurs. It creates a one-to-many relationship between objects. Why Use Observer Pattern? Decouple sender from receivers Easily add/remove notification channels Build event-driven systems Avoid tight coupling Real-Time Scenario In an Order System : When an order is placed → multiple actions should happen Email notification SMS notification Push notification Instead of hardcoding all these inside Order logic, we use observers. Implementation Step 1: Observer Interface public interface IObserver { void Update(string message); } Step 2: Concrete Observers public class EmailService : IObserver { public void Update(string message) { Console.WriteLine($"Email: {message}"); } } public class SmsService : IObserver { public void Up...

Strategy Pattern in C# – Real-Time Example (Invoice Tax Calculation)

What is Strategy Pattern? The Strategy Pattern is a behavioral design pattern that allows you to change the behavior of a class at runtime without modifying its code. Instead of hardcoding logic (like tax calculation), you define multiple strategies and inject the required one dynamically. Why Use Strategy Pattern? Avoid multiple if-else or switch conditions Make logic easily replaceable Follow Open/Closed Principle (open for extension, closed for modification) Improve maintainability Real-Time Scenario In an Invoice Management System , tax calculation can vary: GST (India) No Tax Future: VAT, Service Tax, etc. Instead of modifying the same method every time, we plug different strategies. Implementation Step 1: Create Strategy Interface public interface ITaxStrategy { decimal Calculate(decimal amount); } Step 2: Implement Concrete Strategies public class GstTax : ITaxStrategy { public decimal Calculate(decimal amount)...