Posts

Interpreter Pattern in C# – Real-Time Example (Rule / Expression Evaluation)

Interpreter Pattern in C# – Real-Time Example (Rule / Expression Evaluation) What is Interpreter Pattern? The Interpreter Pattern is a behavioral design pattern used to interpret and evaluate language grammar, expressions, or rules. 👉 Converts expressions into executable logic. It is commonly used in: Rule engines Formula calculators Query parsers Expression evaluators Why Use Interpreter Pattern? Evaluate expressions dynamically Build rule engines Parse custom languages Simplify grammar processing Encapsulate evaluation logic Real-Time Scenario Calculator System: 10 + 5 - 3 👉 Expression needs interpretation and execution. Real-Time Example – Simple Expression Interpreter Step 1: Expression Interface public interface IExpression { int Interpret(); } Step 2: Number Expression public class NumberExpression : IExpression { private readonly int _number; public NumberExpression(int...

Visitor Pattern in C# – Real-Time Example (Adding Operations Without Modifying Objects)

What is Visitor Pattern? The Visitor Pattern is a behavioral design pattern that allows you to add new operations to existing object structures without modifying those classes. 👉 Separate: Object structure Operations/behaviors Why Use Visitor Pattern? Add new functionality easily Avoid modifying existing classes Follow Open/Closed Principle Separate business logic from objects Improve maintainability Real-Time Scenario Invoice System: Need multiple operations: PDF Export Excel Export Tax Calculation Report Generation 👉 Instead of modifying Invoice class repeatedly, use Visitors. Real-Time Example – Invoice Export System Step 1: Visitor Interface public interface IVisitor { void Visit(Invoice invoice); } Step 2: Element Interface public interface IElement { void Accept(IVisitor visitor); } Step 3: Concrete Element public class Invoice : IElement { public decimal A...

Memento Pattern in C# – Real-Time Example (Undo / Restore State)

What is Memento Pattern? The Memento Pattern is a behavioral design pattern that allows you to save and restore an object's previous state without exposing its internal details. 👉 Used mainly for: Undo Rollback Checkpoints History tracking Why Use Memento Pattern? Save object snapshots Restore previous state Implement undo/redo Maintain encapsulation Track history safely Real-Time Scenario Text Editor: User types text Save state Undo changes 👉 Restore previous version easily. Real-Time Example – Text Editor Undo Feature Step 1: Memento Class public class EditorMemento { public string Content { get; } public EditorMemento(string content) { Content = content; } } Step 2: Originator Class public class TextEditor { public string Content { get; set; } // Save state public EditorMemento Save() { return new EditorMemento(Content); ...

Iterator Pattern in C# – Real-Time Example (Sequential Collection Traversal)

What is Iterator Pattern? The Iterator Pattern is a behavioral design pattern that provides a way to access elements of a collection sequentially without exposing its internal structure. 👉 Helps traverse collections safely and uniformly. Why Use Iterator Pattern? Simplify collection traversal Hide internal collection structure Provide uniform access to elements Support custom iteration logic Improve maintainability Real-Time Scenario Examples: Pagination in APIs Traversing invoice items Navigating product lists Iterating menu items 👉 Client accesses items one by one without knowing collection internals. Real-Time Example – Product Collection Step 1: Collection Class public class ProductCollection { private readonly List<string> _products = new(); public void Add(string product) { _products.Add(product); } public Iterator GetIterator() { return new Iterator...

Template Method Pattern in C# – Real-Time Example (Algorithm Skeleton)

What is Template Method Pattern? The Template Method Pattern is a behavioral design pattern that defines the overall structure (template) of an algorithm in a base class, while allowing subclasses to implement specific steps. 👉 Common workflow stays fixed 👉 Individual steps can vary Why Use Template Method Pattern? Reuse common workflow logic Avoid duplicate code Standardize process flow Allow customizable steps Improve maintainability Real-Time Scenario Report Generation: Fetch data Format report Export report Different report types: PDF Report Excel Report 👉 Workflow is same, implementation differs. Real-Time Example – Report Generation System Step 1: Abstract Base Class public abstract class ReportGenerator { // Template Method public void GenerateReport() { GetData(); FormatReport(); ExportReport(); } protected abstract void GetData(); p...

Chain of Responsibility Pattern in C# – Real-Time Example (Request Processing Pipeline)

What is Chain of Responsibility Pattern? The Chain of Responsibility Pattern is a behavioral design pattern where a request is passed through a chain of handlers until one handler processes it. Each handler: Processes the request Or passes it to the next handler 👉 Creates a pipeline-like structure. Why Use Chain of Responsibility Pattern? Reduce tight coupling Build flexible processing pipelines Dynamically add/remove handlers Separate responsibilities cleanly Avoid large if-else chains Real-Time Scenario API Request Pipeline: Authentication Authorization Validation Logging 👉 Request passes through multiple handlers sequentially. Real-Time Example – Request Validation Pipeline Step 1: Abstract Handler public abstract class Handler { protected Handler _nextHandler; public void SetNext(Handler nextHandler) { _nextHandler = nextHandler; } public abstract void Ha...

State Pattern in C# – Real-Time Example (Behavior Based on State)

What is State Pattern? The State Pattern is a behavioral design pattern where an object changes its behavior when its internal state changes. 👉 The object behaves differently depending on its current state. It is similar to a finite state machine. Why Use State Pattern? Remove large if-else/switch statements Organize state-specific behavior Improve maintainability Make state transitions cleaner Follow Open/Closed Principle Real-Time Scenario Order Processing System: Pending Paid Shipped Delivered Cancelled 👉 Order behavior changes based on current status. Real-Time Example – Order State Workflow Step 1: State Interface public interface IOrderState { void Handle(); } Step 2: Concrete States Pending State public class PendingState : IOrderState { public void Handle() { Console.WriteLine("Order is Pending"); } } Paid State public class PaidState : IO...

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

What is Mediator Pattern? The Mediator Pattern is a behavioral design pattern that centralizes communication between multiple objects. Instead of objects communicating directly with each other, they communicate through a mediator. 👉 This reduces tight coupling. Why Use Mediator Pattern? Reduce direct dependencies Simplify object communication Centralize interaction logic Improve maintainability Make systems scalable Real-Time Scenario Chat Application: User A sends message User B receives message User C receives message 👉 Users should not directly reference each other. Mediator handles communication. Real-Time Example – Chat System Step 1: Mediator Class public class ChatMediator { public void Send(string message, User user) { Console.WriteLine($"{user.Name}: {message}"); } } Step 2: User Class public class User { private readonly ChatMediator _mediator; public string N...

Command Pattern in C# – Real-Time Example (Encapsulating Requests)

What is Command Pattern? The Command Pattern is a behavioral design pattern that encapsulates a request as an object. It separates: Sender of request Receiver of request 👉 This allows requests to be: Queued Logged Undone Executed dynamically Why Use Command Pattern? Decouple sender and receiver Support undo/redo Queue operations Centralize action execution Improve flexibility Real-Time Scenario Button Click Actions: Save Delete Update Create Invoice 👉 Each action becomes a command object. Real-Time Example – Invoice Command System Step 1: Command Interface public interface ICommand { void Execute(); } Step 2: Receiver public class InvoiceService { public void CreateInvoice() { Console.WriteLine("Invoice Created"); } public void DeleteInvoice() { Console.WriteLine("Invoice Deleted"); } } Step 3: Concrete Commands Cr...

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

What is Observer Pattern? The Observer Pattern is a behavioral design pattern where one object (Subject) notifies multiple dependent objects (Observers) automatically when its state changes. It follows a: One → Many relationship. Why Use Observer Pattern? Enable event-driven communication Reduce tight coupling Automatically notify subscribers Improve scalability and flexibility Real-Time Scenario Order Placed: Send Email Send SMS Push Notification Update Dashboard 👉 One event triggers multiple actions. Real-Time Example – Order Notification System Step 1: Observer Interface public interface IObserver { void Update(string message); } Step 2: Concrete Observers Email Service public class EmailService : IObserver { public void Update(string message) { Console.WriteLine($"Email: {message}"); } } SMS Service public class SmsService : IObserver { public void Update(s...

Strategy Pattern in C# – Real-Time Example (Dynamic Behavior Switching)

What is Strategy Pattern? The Strategy Pattern is a behavioral design pattern that allows you to change an object's behavior at runtime by selecting different algorithms or strategies dynamically. Instead of using large: if-else switch We encapsulate behaviors into separate classes. Why Use Strategy Pattern? Remove complex if-else conditions Change behavior dynamically Follow Open/Closed Principle Improve maintainability and scalability Real-Time Scenario Invoice System: GST Tax No Tax International Tax 👉 Tax calculation changes dynamically based on customer type/location. Real-Time Example – Invoice Tax Calculation Step 1: Strategy Interface public interface ITaxStrategy { decimal Calculate(decimal amount); } Step 2: Concrete Strategies GST Tax public class GstTax : ITaxStrategy { public decimal Calculate(decimal amount) { return amount * 0.18m; } } No Tax public class NoT...

Behavioral Design Patterns in C# / .NET

What are Behavioral Patterns? Behavioral patterns focus on communication and interaction between objects. They define: How objects communicate How responsibilities are distributed How behavior changes dynamically Purpose of Behavioral Patterns Improve communication flow Reduce tight coupling Make behavior flexible Simplify object interactions Improve maintainability Types of Behavioral Patterns Pattern Purpose Real-Time Example Strategy Change behavior dynamically Tax/Discount calculation Observer Notify multiple objects Email/SMS notifications Command Encapsulate requests Button click actions Mediator Central communication control Chat system State Change behavior based on state Order status Chain of Responsibility Pass request thr...

Flyweight Pattern in C# – Real-Time Example (Memory Optimization)

What is Flyweight Pattern? The Flyweight Pattern is a structural design pattern that reduces memory usage by sharing common objects instead of creating duplicate objects. It is mainly used when applications create a large number of similar objects. Why Use Flyweight Pattern? Reduce memory consumption Improve performance Reuse shared objects Avoid duplicate object creation Real-Time Scenario Examples: Thousands of icons/images in UI Characters in text editor Game objects (trees, bullets) Cache systems 👉 Instead of creating many identical objects, reuse existing ones. Real-Time Example – Icon System Suppose a UI application displays: Many file icons Same image repeated multiple times Without Flyweight: 1000 objects → high memory usage With Flyweight: 1 shared icon object reused Real-Time Example – Document Editor Step 1: Flyweight Object public class Character { private reado...