Master Design Patterns in C#
Your comprehensive guide to implementing design patterns in C# for better software architecture
Design Patterns
Creational Patterns
Singleton Pattern
Ensures a class has only one instance and provides a global point of access to it. This pattern is particularly useful for managing shared resources and maintaining global state.
- Thread-safe implementation using Lazy
for better performance - Lazy initialization to defer object creation until first use
- Global state management for application-wide settings
- Resource pooling for database connections and thread pools
- Configuration management and logging services
Common Use Cases:
- Database connection managers
- Configuration settings
- Logging services
- Cache managers
- Thread pools
Implementation Considerations:
- Thread safety in multi-threaded environments
- Lazy vs eager initialization trade-offs
- Testing challenges and dependency injection
- Memory management and resource cleanup
Factory Method Pattern
Defines an interface for creating objects but lets subclasses decide which class to instantiate. This pattern promotes loose coupling and follows the Open/Closed Principle.
- Object creation abstraction through interfaces
- Extensible design for new product types
- Dependency reduction in client code
- Centralized object creation logic
- Support for complex initialization
Common Use Cases:
- UI component creation
- Database connection factories
- Document processing systems
- Plugin architectures
- Cross-platform implementations
Implementation Considerations:
- Parameterized factory methods
- Static vs instance factory methods
- Error handling and validation
- Integration with dependency injection
Abstract Factory Pattern
Provides an interface for creating families of related objects without specifying their concrete classes. This pattern ensures that created objects are compatible with each other.
- Product family creation with consistent interfaces
- System independence through abstraction
- Ensures product compatibility
- Supports multiple implementations
- Facilitates product switching
Common Use Cases:
- Cross-platform UI frameworks
- Database abstraction layers
- Theme systems
- Plugin architectures
- Multi-vendor integrations
Implementation Considerations:
- Factory hierarchy design
- Product interface design
- Error handling strategies
- Testing and mocking
Builder Pattern
Separates the construction of a complex object from its representation, allowing the same construction process to create different representations.
- Step-by-step construction of complex objects
- Object composition with validation
- Immutable object creation
- Fluent interface support
- Parameter validation and error handling
Common Use Cases:
- Complex object construction
- Query builders
- Document builders
- Configuration objects
- Immutable object creation
Implementation Considerations:
- Builder interface design
- Validation strategies
- Error handling approaches
- Immutable vs mutable objects
Prototype Pattern
Creates new objects by cloning an existing object, known as the prototype. This pattern is useful when object creation is expensive or when objects have many shared properties.
- Object cloning with deep or shallow copy
- Reduced subclassing requirements
- Dynamic configuration of objects
- Performance optimization
- State preservation
Common Use Cases:
- Object caching
- Game development
- Document templates
- UI component cloning
- Configuration objects
Implementation Considerations:
- Deep vs shallow copying
- Clone method implementation
- Circular reference handling
- Performance implications
Structural Patterns
Adapter Pattern
Allows incompatible interfaces to work together by wrapping an object. This pattern is particularly useful when integrating legacy code or third-party components into a new system.
- Interface compatibility through wrapping
- Legacy code integration without modification
- Reusable components across systems
- Multiple interface support
- Gradual system migration
Common Use Cases:
- Legacy system integration
- Third-party library adaptation
- API version compatibility
- Database driver adaptation
- UI framework integration
Implementation Considerations:
- Object vs class adapters
- Multiple interface adaptation
- Performance overhead
- Error handling strategies
Bridge Pattern
Decouples an abstraction from its implementation so that both can vary independently. This pattern is useful for managing complex hierarchies and platform-specific implementations.
- Implementation separation through interfaces
- Multiple platform support
- Extensible design for both hierarchies
- Runtime implementation switching
- Reduced inheritance complexity
Common Use Cases:
- Cross-platform UI frameworks
- Database abstraction layers
- Device driver implementations
- Plugin architectures
- Multi-vendor integrations
Implementation Considerations:
- Interface design for both hierarchies
- Implementation selection strategy
- Error handling approaches
- Testing and mocking
Composite Pattern
Composes objects into tree structures to represent part-whole hierarchies. This pattern allows clients to treat individual objects and compositions uniformly.
- Tree structure representation
- Uniform treatment of components
- Recursive composition
- Dynamic structure modification
- Component operation delegation
Common Use Cases:
- File system structures
- UI component hierarchies
- Organization charts
- Menu systems
- Document structures
Implementation Considerations:
- Child management strategies
- Operation propagation
- Type safety
- Performance optimization
Decorator Pattern
Attaches additional responsibilities to objects dynamically. This pattern provides a flexible alternative to subclassing for extending functionality.
- Dynamic behavior extension
- Single responsibility principle
- Open for extension
- Multiple decorator composition
- Runtime behavior modification
Common Use Cases:
- Stream processing
- UI component enhancement
- Logging and monitoring
- Security and validation
- Caching and performance
Implementation Considerations:
- Interface design
- Decorator ordering
- Performance implications
- Testing strategies
Facade Pattern
Provides a simplified interface to a complex subsystem. This pattern promotes loose coupling and makes the subsystem easier to use.
- Simplified interface to complex systems
- Subsystem decoupling
- Layer abstraction
- Reduced dependencies
- Improved maintainability
Common Use Cases:
- Library wrappers
- API simplification
- Subsystem access control
- Legacy system modernization
- Service layer implementation
Implementation Considerations:
- Interface design
- Error handling
- Performance optimization
- Testing strategies
Flyweight Pattern
Reduces memory usage by sharing data between similar objects. This pattern is particularly useful when dealing with large numbers of similar objects.
- Memory optimization through sharing
- Shared state management
- Intrinsic vs extrinsic state
- Object pooling
- Cache management
Common Use Cases:
- Text processing
- Game development
- UI component rendering
- Document processing
- Cache implementations
Implementation Considerations:
- State separation
- Thread safety
- Memory management
- Performance optimization
Proxy Pattern
Provides a surrogate or placeholder for another object to control access to it. This pattern is useful for implementing cross-cutting concerns and controlling object access.
- Access control and security
- Lazy initialization
- Remote access management
- Caching and performance
- Logging and monitoring
Common Use Cases:
- Remote service access
- Access control
- Lazy loading
- Caching
- Logging and monitoring
Implementation Considerations:
- Proxy type selection
- Error handling
- Performance implications
- Testing strategies
Behavioral Patterns
Chain of Responsibility
Passes a request along a chain of handlers, each deciding whether to process the request or pass it to the next handler. This pattern promotes loose coupling and flexibility in request handling.
- Request handling through a chain
- Dynamic chain modification
- Single responsibility principle
- Flexible request processing
- Fallback mechanisms
Common Use Cases:
- Event handling systems
- Middleware pipelines
- Exception handling
- Request validation
- Logging and monitoring
Implementation Considerations:
- Chain construction
- Handler ordering
- Request termination
- Error handling
Command Pattern
Encapsulates a request as an object, allowing parameterization of clients with different requests, queuing, and logging of requests. This pattern supports undoable operations and command queuing.
- Request encapsulation
- Undo/redo operations
- Command queuing
- Operation logging
- Transaction management
Common Use Cases:
- UI command handling
- Undo/redo functionality
- Job scheduling
- Macro recording
- Remote execution
Implementation Considerations:
- Command interface design
- State management
- Error handling
- Command composition
Iterator Pattern
Provides a way to access elements of a collection sequentially without exposing its underlying representation. This pattern simplifies collection traversal and supports multiple traversal algorithms.
- Collection traversal abstraction
- Multiple iterator support
- Encapsulated iteration logic
- Lazy evaluation
- Parallel iteration
Common Use Cases:
- Collection traversal
- Custom iteration logic
- Lazy loading
- Parallel processing
- Tree traversal
Implementation Considerations:
- Iterator interface design
- State management
- Concurrent modification
- Performance optimization
Mediator Pattern
Defines an object that encapsulates how a set of objects interact. This pattern promotes loose coupling by keeping objects from referring to each other explicitly.
- Object communication centralization
- Centralized control
- Loose coupling
- Simplified object protocols
- Event handling
Common Use Cases:
- UI component coordination
- Event handling systems
- Message routing
- Workflow management
- Service orchestration
Implementation Considerations:
- Mediator interface design
- Event handling
- Error propagation
- Testing strategies
Memento Pattern
Captures and externalizes an object's internal state without violating encapsulation. This pattern enables undo/redo operations and state restoration.
- State restoration
- Undo mechanism
- Snapshot management
- Encapsulated state
- History tracking
Common Use Cases:
- Undo/redo functionality
- Checkpoint systems
- State persistence
- Transaction management
- Game state saving
Implementation Considerations:
- State serialization
- Memory management
- Partial state saving
- Version control
Observer Pattern
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.
- Event handling
- Loose coupling
- State synchronization
- Publish-subscribe model
- Reactive programming
Common Use Cases:
- Event handling systems
- UI updates
- Data binding
- Message queues
- Reactive systems
Implementation Considerations:
- Notification strategies
- Memory management
- Thread safety
- Error handling
State Pattern
Allows an object to alter its behavior when its internal state changes. This pattern encapsulates state-specific behavior and state transitions.
- State transitions
- Behavior encapsulation
- Conditional logic
- State-specific behavior
- Clean state management
Common Use Cases:
- Workflow management
- Game state machines
- UI state handling
- Process management
- Order processing
Implementation Considerations:
- State transition logic
- State persistence
- Error handling
- Testing strategies
Strategy Pattern
Defines a family of algorithms, encapsulates each one, and makes them interchangeable. This pattern enables algorithm selection at runtime.
- Algorithm selection
- Runtime flexibility
- Behavior encapsulation
- Algorithm composition
- Clean code organization
Common Use Cases:
- Sorting algorithms
- Payment processing
- Compression algorithms
- Validation strategies
- Pricing calculations
Implementation Considerations:
- Strategy selection
- Parameter passing
- Performance optimization
- Testing strategies
Template Method Pattern
Defines the skeleton of an algorithm in a method, deferring some steps to subclasses. This pattern promotes code reuse and the Hollywood Principle.
- Algorithm structure
- Code reuse
- Extension points
- Inverted control
- Consistent behavior
Common Use Cases:
- Framework design
- Algorithm customization
- Process workflows
- UI component lifecycle
- Data processing pipelines
Implementation Considerations:
- Hook design
- Default implementations
- Error handling
- Testing strategies
Visitor Pattern
Represents an operation to be performed on elements of an object structure. This pattern allows adding new operations without changing the classes of the elements.
- Operation separation
- New operations
- Double dispatch
- Extensible design
- Clean separation of concerns
Common Use Cases:
- AST processing
- Document processing
- Code generation
- Serialization
- Validation
Implementation Considerations:
- Visitor interface design
- Accept method implementation
- State management
- Performance optimization
Architectural Patterns
MVC Pattern
Separates an application into three main components: Model (data), View (UI), and Controller (logic). This pattern promotes separation of concerns and maintainable code structure.
- Separation of concerns
- Code organization
- Maintainable structure
- Testable components
- Reusable views
Common Use Cases:
- Web applications
- Desktop applications
- Mobile applications
- Enterprise systems
- Content management
Implementation Considerations:
- Component communication
- Data binding
- Routing
- Testing strategies
MVVM Pattern
Extends MVC by introducing a ViewModel that manages the presentation logic and state. This pattern is particularly useful for data binding and reactive UI updates.
- Data binding
- Reactive updates
- Testable presentation logic
- Clean separation
- State management
Common Use Cases:
- Modern web applications
- Single-page applications
- Desktop applications
- Mobile applications
- Enterprise systems
Implementation Considerations:
- Data binding setup
- Command handling
- Validation
- Testing strategies
Repository Pattern
Abstracts the data access layer, providing a collection-like interface for accessing domain objects. This pattern centralizes data access logic and promotes testability.
- Data access abstraction
- Domain-centric design
- Testable data access
- Clean architecture
- Consistent interface
Common Use Cases:
- Data access layer
- Domain-driven design
- Test-driven development
- Enterprise applications
- Microservices
Implementation Considerations:
- Interface design
- Query optimization
- Caching strategy
- Error handling
Unit of Work Pattern
Maintains a list of objects affected by a business transaction and coordinates the writing out of changes. This pattern ensures data consistency and transaction management.
- Transaction management
- Change tracking
- Atomic operations
- Data consistency
- Optimistic concurrency
Common Use Cases:
- Database operations
- Transaction management
- Data consistency
- Change tracking
- Batch processing
Implementation Considerations:
- Transaction scope
- Change tracking
- Error handling
- Performance optimization
Concurrency Patterns
Active Object Pattern
Decouples method execution from method invocation, allowing asynchronous processing. This pattern is useful for handling concurrent operations and improving responsiveness.
- Asynchronous execution
- Method queuing
- Thread safety
- Responsive design
- Resource management
Common Use Cases:
- UI responsiveness
- Background processing
- Resource management
- Event handling
- Service operations
Implementation Considerations:
- Queue management
- Thread safety
- Error handling
- Resource cleanup
Balking Pattern
Prevents an object from executing an action if it's in an inappropriate state. This pattern is useful for handling concurrent operations and preventing race conditions.
- State checking
- Operation prevention
- Thread safety
- Resource protection
- Error handling
Common Use Cases:
- Resource management
- State validation
- Operation control
- Error prevention
- Concurrent operations
Implementation Considerations:
- State validation
- Error handling
- Thread safety
- Performance impact
Double-Checked Locking Pattern
Reduces the overhead of acquiring a lock by first testing the locking criterion without actually acquiring the lock. This pattern optimizes performance in concurrent scenarios.
- Performance optimization
- Lazy initialization
- Thread safety
- Resource efficiency
- Memory optimization
Common Use Cases:
- Singleton initialization
- Resource management
- Cache implementation
- Lazy loading
- Performance optimization
Implementation Considerations:
- Memory model
- Thread safety
- Performance impact
- Error handling
Guarded Suspension Pattern
Manages operations that require a specific condition to be met before proceeding. This pattern is useful for handling concurrent operations and resource availability.
- Condition checking
- Operation suspension
- Resource management
- Thread safety
- Error handling
Common Use Cases:
- Resource management
- Operation queuing
- Condition handling
- Concurrent operations
- Error prevention
Implementation Considerations:
- Condition checking
- Thread safety
- Error handling
- Performance impact
Monitor Object Pattern
Synchronizes concurrent access to an object's methods, ensuring thread safety. This pattern is useful for managing shared resources and preventing race conditions.
- Method synchronization
- Thread safety
- Resource protection
- Condition handling
- Error prevention
Common Use Cases:
- Resource management
- Concurrent operations
- Thread safety
- Error prevention
- State management
Implementation Considerations:
- Synchronization strategy
- Thread safety
- Error handling
- Performance impact
Reactor Pattern
Handles service requests delivered concurrently to a service handler. This pattern is useful for managing multiple concurrent operations and improving scalability.
- Event handling
- Concurrent processing
- Scalability
- Resource management
- Error handling
Common Use Cases:
- Network servers
- Event processing
- Concurrent operations
- Resource management
- Scalable systems
Implementation Considerations:
- Event handling
- Resource management
- Error handling
- Performance optimization
Read-Write Lock Pattern
Allows multiple readers to access a resource simultaneously while ensuring exclusive access for writers. This pattern optimizes performance in concurrent read-heavy scenarios.
- Concurrent reading
- Exclusive writing
- Performance optimization
- Resource protection
- Thread safety
Common Use Cases:
- Database operations
- Cache management
- Resource sharing
- Concurrent access
- Performance optimization
Implementation Considerations:
- Lock management
- Thread safety
- Performance impact
- Error handling
Scheduler Pattern
Manages the execution of tasks based on priority, timing, or other criteria. This pattern is useful for handling concurrent operations and resource allocation.
- Task scheduling
- Priority management
- Resource allocation
- Concurrent execution
- Error handling
Common Use Cases:
- Task scheduling
- Resource management
- Priority handling
- Concurrent operations
- System optimization
Implementation Considerations:
- Scheduling strategy
- Resource management
- Error handling
- Performance optimization
Practical Code Examples
Singleton Pattern Example
This example demonstrates a thread-safe implementation of the Singleton pattern:
public sealed class Singleton
{
private static readonly Lazy _instance =
new Lazy(() => new Singleton());
public static Singleton Instance => _instance.Value;
private Singleton() { }
public void DoSomething()
{
Console.WriteLine("Singleton is doing something...");
}
}
// Usage
var singleton = Singleton.Instance;
singleton.DoSomething();
Factory Method Pattern Example
This example shows how to implement the Factory Method pattern:
public abstract class Creator
{
public abstract IProduct FactoryMethod();
public string SomeOperation()
{
var product = FactoryMethod();
return $"Creator: {product.Operation()}";
}
}
public class ConcreteCreator1 : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProduct1();
}
}
public class ConcreteCreator2 : Creator
{
public override IProduct FactoryMethod()
{
return new ConcreteProduct2();
}
}
public interface IProduct
{
string Operation();
}
public class ConcreteProduct1 : IProduct
{
public string Operation()
{
return "Result of ConcreteProduct1";
}
}
public class ConcreteProduct2 : IProduct
{
public string Operation()
{
return "Result of ConcreteProduct2";
}
}
Observer Pattern Example
This example demonstrates the Observer pattern implementation:
public interface IObserver
{
void Update(string message);
}
public interface ISubject
{
void Attach(IObserver observer);
void Detach(IObserver observer);
void Notify();
}
public class Subject : ISubject
{
private List _observers = new List();
private string _state;
public string State
{
get => _state;
set
{
_state = value;
Notify();
}
}
public void Attach(IObserver observer)
{
_observers.Add(observer);
}
public void Detach(IObserver observer)
{
_observers.Remove(observer);
}
public void Notify()
{
foreach (var observer in _observers)
{
observer.Update(_state);
}
}
}
public class ConcreteObserver : IObserver
{
private string _name;
public ConcreteObserver(string name)
{
_name = name;
}
public void Update(string message)
{
Console.WriteLine($"{_name} received: {message}");
}
}
Dependency Inversion Principle Example
This example demonstrates a complete implementation of DIP in a notification system:
// Core interfaces
public interface INotificationService
{
void SendNotification(string recipient, string subject, string message);
}
public interface ILogger
{
void LogInfo(string message);
void LogError(string message);
}
public interface IConfigurationService
{
string GetSetting(string key);
void SaveSetting(string key, string value);
}
// Concrete implementations
public class EmailNotificationService : INotificationService
{
private readonly ILogger _logger;
private readonly IConfigurationService _config;
private readonly SmtpClient _smtpClient;
public EmailNotificationService(
ILogger logger,
IConfigurationService config,
SmtpClient smtpClient)
{
_logger = logger;
_config = config;
_smtpClient = smtpClient;
}
public void SendNotification(string recipient, string subject, string message)
{
try
{
var mailMessage = new MailMessage
{
From = new MailAddress(_config.GetSetting("FromEmail")),
Subject = subject,
Body = message,
IsBodyHtml = true
};
mailMessage.To.Add(recipient);
_smtpClient.Send(mailMessage);
_logger.LogInfo($"Email sent to {recipient}");
}
catch (Exception ex)
{
_logger.LogError($"Failed to send email to {recipient}: {ex.Message}");
throw;
}
}
}
public class SmsNotificationService : INotificationService
{
private readonly ILogger _logger;
private readonly IConfigurationService _config;
public SmsNotificationService(
ILogger logger,
IConfigurationService config)
{
_logger = logger;
_config = config;
}
public void SendNotification(string recipient, string subject, string message)
{
try
{
// Implement SMS sending logic
_logger.LogInfo($"SMS sent to {recipient}");
}
catch (Exception ex)
{
_logger.LogError($"Failed to send SMS to {recipient}: {ex.Message}");
throw;
}
}
}
public class FileLogger : ILogger
{
private readonly string _logFilePath;
public FileLogger(string logFilePath)
{
_logFilePath = logFilePath;
}
public void LogInfo(string message)
{
var logMessage = $"[INFO] {DateTime.Now}: {message}";
File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
}
public void LogError(string message)
{
var logMessage = $"[ERROR] {DateTime.Now}: {message}";
File.AppendAllText(_logFilePath, logMessage + Environment.NewLine);
}
}
public class AppSettingsConfiguration : IConfigurationService
{
private readonly Dictionary _settings;
public AppSettingsConfiguration()
{
_settings = new Dictionary();
}
public string GetSetting(string key)
{
return _settings.TryGetValue(key, out var value) ? value : null;
}
public void SaveSetting(string key, string value)
{
_settings[key] = value;
}
}
// Main service
public class NotificationManager
{
private readonly INotificationService _notificationService;
private readonly ILogger _logger;
public NotificationManager(
INotificationService notificationService,
ILogger logger)
{
_notificationService = notificationService;
_logger = logger;
}
public void SendWelcomeNotification(string recipient)
{
try
{
_notificationService.SendNotification(
recipient,
"Welcome to Our Service",
"Thank you for joining our service!"
);
}
catch (Exception ex)
{
_logger.LogError($"Failed to send welcome notification: {ex.Message}");
throw;
}
}
public void SendPasswordResetNotification(string recipient)
{
try
{
_notificationService.SendNotification(
recipient,
"Password Reset Request",
"Click here to reset your password."
);
}
catch (Exception ex)
{
_logger.LogError($"Failed to send password reset notification: {ex.Message}");
throw;
}
}
}
// Usage example
public class Program
{
public static void Main()
{
// Setup dependencies
var logger = new FileLogger("notifications.log");
var config = new AppSettingsConfiguration();
config.SaveSetting("FromEmail", "noreply@example.com");
// Create notification service
var smtpClient = new SmtpClient();
var emailService = new EmailNotificationService(logger, config, smtpClient);
// Create notification manager
var notificationManager = new NotificationManager(emailService, logger);
// Send notifications
notificationManager.SendWelcomeNotification("user@example.com");
notificationManager.SendPasswordResetNotification("user@example.com");
}
}
Abstract Factory Pattern Example
This example demonstrates a complete implementation of the Abstract Factory pattern for creating UI components:
// Abstract Factory Pattern
public interface IButton
{
void Render();
void OnClick();
}
public interface ITextBox
{
void Render();
void SetText(string text);
}
public interface ICheckBox
{
void Render();
void SetChecked(bool isChecked);
}
public interface IGUIFactory
{
IButton CreateButton();
ITextBox CreateTextBox();
ICheckBox CreateCheckBox();
}
// Windows UI Components
public class WindowsButton : IButton
{
public void Render()
{
Console.WriteLine("Rendering Windows button");
}
public void OnClick()
{
Console.WriteLine("Windows button clicked");
}
}
public class WindowsTextBox : ITextBox
{
public void Render()
{
Console.WriteLine("Rendering Windows textbox");
}
public void SetText(string text)
{
Console.WriteLine($"Windows textbox text set to: {text}");
}
}
public class WindowsCheckBox : ICheckBox
{
public void Render()
{
Console.WriteLine("Rendering Windows checkbox");
}
public void SetChecked(bool isChecked)
{
Console.WriteLine($"Windows checkbox set to: {isChecked}");
}
}
// Mac UI Components
public class MacButton : IButton
{
public void Render()
{
Console.WriteLine("Rendering Mac button");
}
public void OnClick()
{
Console.WriteLine("Mac button clicked");
}
}
public class MacTextBox : ITextBox
{
public void Render()
{
Console.WriteLine("Rendering Mac textbox");
}
public void SetText(string text)
{
Console.WriteLine($"Mac textbox text set to: {text}");
}
}
public class MacCheckBox : ICheckBox
{
public void Render()
{
Console.WriteLine("Rendering Mac checkbox");
}
public void SetChecked(bool isChecked)
{
Console.WriteLine($"Mac checkbox set to: {isChecked}");
}
}
// Concrete Factories
public class WindowsGUIFactory : IGUIFactory
{
public IButton CreateButton()
{
return new WindowsButton();
}
public ITextBox CreateTextBox()
{
return new WindowsTextBox();
}
public ICheckBox CreateCheckBox()
{
return new WindowsCheckBox();
}
}
public class MacGUIFactory : IGUIFactory
{
public IButton CreateButton()
{
return new MacButton();
}
public ITextBox CreateTextBox()
{
return new MacTextBox();
}
public ICheckBox CreateCheckBox()
{
return new MacCheckBox();
}
}
// Client Code
public class Application
{
private readonly IGUIFactory _factory;
private IButton _button;
private ITextBox _textBox;
private ICheckBox _checkBox;
public Application(IGUIFactory factory)
{
_factory = factory;
}
public void CreateUI()
{
_button = _factory.CreateButton();
_textBox = _factory.CreateTextBox();
_checkBox = _factory.CreateCheckBox();
}
public void RenderUI()
{
_button.Render();
_textBox.Render();
_checkBox.Render();
}
public void SimulateUserInteraction()
{
_button.OnClick();
_textBox.SetText("Hello, World!");
_checkBox.SetChecked(true);
}
}
// Usage
public class Program
{
public static void Main()
{
// Create Windows UI
var windowsFactory = new WindowsGUIFactory();
var windowsApp = new Application(windowsFactory);
windowsApp.CreateUI();
windowsApp.RenderUI();
windowsApp.SimulateUserInteraction();
Console.WriteLine("\n---\n");
// Create Mac UI
var macFactory = new MacGUIFactory();
var macApp = new Application(macFactory);
macApp.CreateUI();
macApp.RenderUI();
macApp.SimulateUserInteraction();
}
}
Builder Pattern Example
This example demonstrates a complete implementation of the Builder pattern for creating complex objects:
// Builder Pattern
public class Computer
{
public string CPU { get; set; }
public string RAM { get; set; }
public string Storage { get; set; }
public string GraphicsCard { get; set; }
public string OperatingSystem { get; set; }
public override string ToString()
{
return $"Computer Configuration:\n" +
$"CPU: {CPU}\n" +
$"RAM: {RAM}\n" +
$"Storage: {Storage}\n" +
$"Graphics Card: {GraphicsCard}\n" +
$"Operating System: {OperatingSystem}";
}
}
public interface IComputerBuilder
{
void SetCPU(string cpu);
void SetRAM(string ram);
void SetStorage(string storage);
void SetGraphicsCard(string graphicsCard);
void SetOperatingSystem(string os);
Computer Build();
}
public class GamingComputerBuilder : IComputerBuilder
{
private Computer _computer = new Computer();
public void SetCPU(string cpu)
{
_computer.CPU = cpu;
}
public void SetRAM(string ram)
{
_computer.RAM = ram;
}
public void SetStorage(string storage)
{
_computer.Storage = storage;
}
public void SetGraphicsCard(string graphicsCard)
{
_computer.GraphicsCard = graphicsCard;
}
public void SetOperatingSystem(string os)
{
_computer.OperatingSystem = os;
}
public Computer Build()
{
return _computer;
}
}
public class OfficeComputerBuilder : IComputerBuilder
{
private Computer _computer = new Computer();
public void SetCPU(string cpu)
{
_computer.CPU = cpu;
}
public void SetRAM(string ram)
{
_computer.RAM = ram;
}
public void SetStorage(string storage)
{
_computer.Storage = storage;
}
public void SetGraphicsCard(string graphicsCard)
{
_computer.GraphicsCard = graphicsCard;
}
public void SetOperatingSystem(string os)
{
_computer.OperatingSystem = os;
}
public Computer Build()
{
return _computer;
}
}
public class ComputerDirector
{
private readonly IComputerBuilder _builder;
public ComputerDirector(IComputerBuilder builder)
{
_builder = builder;
}
public void BuildGamingComputer()
{
_builder.SetCPU("Intel Core i9-13900K");
_builder.SetRAM("32GB DDR5");
_builder.SetStorage("2TB NVMe SSD");
_builder.SetGraphicsCard("NVIDIA RTX 4090");
_builder.SetOperatingSystem("Windows 11 Pro");
}
public void BuildOfficeComputer()
{
_builder.SetCPU("Intel Core i5-12400");
_builder.SetRAM("16GB DDR4");
_builder.SetStorage("512GB SSD");
_builder.SetGraphicsCard("Intel UHD Graphics 730");
_builder.SetOperatingSystem("Windows 11 Home");
}
}
// Usage
public class Program
{
public static void Main()
{
// Build a gaming computer
var gamingBuilder = new GamingComputerBuilder();
var gamingDirector = new ComputerDirector(gamingBuilder);
gamingDirector.BuildGamingComputer();
var gamingComputer = gamingBuilder.Build();
Console.WriteLine("Gaming Computer:");
Console.WriteLine(gamingComputer);
Console.WriteLine("\n---\n");
// Build an office computer
var officeBuilder = new OfficeComputerBuilder();
var officeDirector = new ComputerDirector(officeBuilder);
officeDirector.BuildOfficeComputer();
var officeComputer = officeBuilder.Build();
Console.WriteLine("Office Computer:");
Console.WriteLine(officeComputer);
}
}
Decorator Pattern Example
This example demonstrates a complete implementation of the Decorator pattern for adding functionality to objects:
// Decorator Pattern
public interface IStream
{
void Write(string data);
string Read();
}
public class FileStream : IStream
{
private string _content = "";
public void Write(string data)
{
_content = data;
Console.WriteLine($"Writing to file: {data}");
}
public string Read()
{
Console.WriteLine($"Reading from file: {_content}");
return _content;
}
}
public abstract class StreamDecorator : IStream
{
protected IStream _stream;
public StreamDecorator(IStream stream)
{
_stream = stream;
}
public virtual void Write(string data)
{
_stream.Write(data);
}
public virtual string Read()
{
return _stream.Read();
}
}
public class EncryptionDecorator : StreamDecorator
{
public EncryptionDecorator(IStream stream) : base(stream)
{
}
public override void Write(string data)
{
string encryptedData = Encrypt(data);
base.Write(encryptedData);
}
public override string Read()
{
string encryptedData = base.Read();
return Decrypt(encryptedData);
}
private string Encrypt(string data)
{
// Simple encryption for demonstration
return $"ENCRYPTED({data})";
}
private string Decrypt(string data)
{
// Simple decryption for demonstration
return data.Replace("ENCRYPTED(", "").Replace(")", "");
}
}
public class CompressionDecorator : StreamDecorator
{
public CompressionDecorator(IStream stream) : base(stream)
{
}
public override void Write(string data)
{
string compressedData = Compress(data);
base.Write(compressedData);
}
public override string Read()
{
string compressedData = base.Read();
return Decompress(compressedData);
}
private string Compress(string data)
{
// Simple compression for demonstration
return $"COMPRESSED({data})";
}
private string Decompress(string data)
{
// Simple decompression for demonstration
return data.Replace("COMPRESSED(", "").Replace(")", "");
}
}
public class LoggingDecorator : StreamDecorator
{
public LoggingDecorator(IStream stream) : base(stream)
{
}
public override void Write(string data)
{
Console.WriteLine($"Logging: Writing data: {data}");
base.Write(data);
}
public override string Read()
{
string data = base.Read();
Console.WriteLine($"Logging: Reading data: {data}");
return data;
}
}
// Usage
public class Program
{
public static void Main()
{
// Create a basic file stream
IStream fileStream = new FileStream();
// Add encryption
IStream encryptedStream = new EncryptionDecorator(fileStream);
encryptedStream.Write("Sensitive Data");
Console.WriteLine($"Read: {encryptedStream.Read()}");
Console.WriteLine("\n---\n");
// Add compression
IStream compressedStream = new CompressionDecorator(fileStream);
compressedStream.Write("Large Data");
Console.WriteLine($"Read: {compressedStream.Read()}");
Console.WriteLine("\n---\n");
// Combine decorators
IStream secureCompressedStream = new CompressionDecorator(
new EncryptionDecorator(
new LoggingDecorator(fileStream)
)
);
secureCompressedStream.Write("Secure Compressed Data");
Console.WriteLine($"Read: {secureCompressedStream.Read()}");
}
}
Command Pattern Example
This example demonstrates a complete implementation of the Command pattern for implementing undoable operations:
// Command Pattern
public interface ICommand
{
void Execute();
void Undo();
}
public class Document
{
private string _content = "";
private string _fontName = "Arial";
private int _fontSize = 12;
public void InsertText(string text)
{
_content += text;
Console.WriteLine($"Inserted text: {text}");
}
public void DeleteText(int length)
{
if (length <= _content.Length)
{
string deletedText = _content.Substring(_content.Length - length);
_content = _content.Substring(0, _content.Length - length);
Console.WriteLine($"Deleted text: {deletedText}");
}
}
public void SetFont(string fontName)
{
_fontName = fontName;
Console.WriteLine($"Font set to: {fontName}");
}
public void SetFontSize(int size)
{
_fontSize = size;
Console.WriteLine($"Font size set to: {size}");
}
public string GetContent()
{
return _content;
}
public string GetFont()
{
return _fontName;
}
public int GetFontSize()
{
return _fontSize;
}
}
public class InsertTextCommand : ICommand
{
private readonly Document _document;
private readonly string _text;
public InsertTextCommand(Document document, string text)
{
_document = document;
_text = text;
}
public void Execute()
{
_document.InsertText(_text);
}
public void Undo()
{
_document.DeleteText(_text.Length);
}
}
public class DeleteTextCommand : ICommand
{
private readonly Document _document;
private readonly int _length;
private string _deletedText;
public DeleteTextCommand(Document document, int length)
{
_document = document;
_length = length;
}
public void Execute()
{
_deletedText = _document.GetContent().Substring(_document.GetContent().Length - _length);
_document.DeleteText(_length);
}
public void Undo()
{
_document.InsertText(_deletedText);
}
}
public class SetFontCommand : ICommand
{
private readonly Document _document;
private readonly string _newFont;
private string _oldFont;
public SetFontCommand(Document document, string newFont)
{
_document = document;
_newFont = newFont;
}
public void Execute()
{
_oldFont = _document.GetFont();
_document.SetFont(_newFont);
}
public void Undo()
{
_document.SetFont(_oldFont);
}
}
public class SetFontSizeCommand : ICommand
{
private readonly Document _document;
private readonly int _newSize;
private int _oldSize;
public SetFontSizeCommand(Document document, int newSize)
{
_document = document;
_newSize = newSize;
}
public void Execute()
{
_oldSize = _document.GetFontSize();
_document.SetFontSize(_newSize);
}
public void Undo()
{
_document.SetFontSize(_oldSize);
}
}
public class DocumentEditor
{
private readonly Document _document;
private readonly Stack _undoStack;
private readonly Stack _redoStack;
public DocumentEditor()
{
_document = new Document();
_undoStack = new Stack();
_redoStack = new Stack();
}
public void ExecuteCommand(ICommand command)
{
command.Execute();
_undoStack.Push(command);
_redoStack.Clear();
}
public void Undo()
{
if (_undoStack.Count > 0)
{
ICommand command = _undoStack.Pop();
command.Undo();
_redoStack.Push(command);
}
}
public void Redo()
{
if (_redoStack.Count > 0)
{
ICommand command = _redoStack.Pop();
command.Execute();
_undoStack.Push(command);
}
}
public string GetContent()
{
return _document.GetContent();
}
}
// Usage
public class Program
{
public static void Main()
{
var editor = new DocumentEditor();
// Execute some commands
editor.ExecuteCommand(new InsertTextCommand(editor._document, "Hello, "));
editor.ExecuteCommand(new InsertTextCommand(editor._document, "World!"));
editor.ExecuteCommand(new SetFontCommand(editor._document, "Times New Roman"));
editor.ExecuteCommand(new SetFontSizeCommand(editor._document, 14));
Console.WriteLine($"Content: {editor.GetContent()}");
// Undo some commands
editor.Undo(); // Undo font size
editor.Undo(); // Undo font
editor.Undo(); // Undo "World!"
Console.WriteLine($"After undo: {editor.GetContent()}");
// Redo some commands
editor.Redo(); // Redo "World!"
editor.Redo(); // Redo font
Console.WriteLine($"After redo: {editor.GetContent()}");
}
}
Iterator Pattern Example
This example demonstrates a complete implementation of the Iterator pattern for traversing collections:
// Iterator Pattern
public interface IIterator
{
bool HasNext();
T Next();
void Reset();
}
public interface ICollection
{
IIterator CreateIterator();
int Count { get; }
T this[int index] { get; }
}
public class ArrayIterator : IIterator
{
private readonly ICollection _collection;
private int _currentIndex = -1;
public ArrayIterator(ICollection collection)
{
_collection = collection;
}
public bool HasNext()
{
return _currentIndex < _collection.Count - 1;
}
public T Next()
{
if (HasNext())
{
_currentIndex++;
return _collection[_currentIndex];
}
throw new InvalidOperationException("No more elements");
}
public void Reset()
{
_currentIndex = -1;
}
}
public class CustomCollection : ICollection
{
private readonly T[] _items;
public CustomCollection(T[] items)
{
_items = items;
}
public int Count => _items.Length;
public T this[int index] => _items[index];
public IIterator CreateIterator()
{
return new ArrayIterator(this);
}
}
// Usage
public class Program
{
public static void Main()
{
var numbers = new CustomCollection(new[] { 1, 2, 3, 4, 5 });
var iterator = numbers.CreateIterator();
Console.WriteLine("Forward iteration:");
while (iterator.HasNext())
{
Console.WriteLine(iterator.Next());
}
iterator.Reset();
Console.WriteLine("\nBackward iteration:");
var list = new List();
while (iterator.HasNext())
{
list.Add(iterator.Next());
}
for (int i = list.Count - 1; i >= 0; i--)
{
Console.WriteLine(list[i]);
}
}
}
Mediator Pattern Example
This example demonstrates a complete implementation of the Mediator pattern for coordinating communication between components:
// Mediator Pattern
public interface IMediator
{
void Notify(object sender, string eventName, object data = null);
}
public interface IColleague
{
void SetMediator(IMediator mediator);
}
public class ChatRoom : IMediator
{
private readonly List _users = new List();
public void RegisterUser(User user)
{
_users.Add(user);
user.SetMediator(this);
}
public void Notify(object sender, string eventName, object data = null)
{
if (eventName == "SendMessage")
{
var message = (Message)data;
foreach (var user in _users.Where(u => u != sender))
{
user.ReceiveMessage(message);
}
}
}
}
public class Message
{
public string Sender { get; set; }
public string Content { get; set; }
public DateTime Timestamp { get; set; }
public Message(string sender, string content)
{
Sender = sender;
Content = content;
Timestamp = DateTime.Now;
}
}
public class User : IColleague
{
private IMediator _mediator;
public string Name { get; }
public User(string name)
{
Name = name;
}
public void SetMediator(IMediator mediator)
{
_mediator = mediator;
}
public void SendMessage(string content)
{
var message = new Message(Name, content);
_mediator.Notify(this, "SendMessage", message);
}
public void ReceiveMessage(Message message)
{
Console.WriteLine($"[{message.Timestamp}] {message.Sender} to {Name}: {message.Content}");
}
}
// Usage
public class Program
{
public static void Main()
{
var chatRoom = new ChatRoom();
var alice = new User("Alice");
var bob = new User("Bob");
var charlie = new User("Charlie");
chatRoom.RegisterUser(alice);
chatRoom.RegisterUser(bob);
chatRoom.RegisterUser(charlie);
alice.SendMessage("Hello everyone!");
bob.SendMessage("Hi Alice!");
charlie.SendMessage("Hey guys, how's it going?");
}
}
Memento Pattern Example
This example demonstrates a complete implementation of the Memento pattern for saving and restoring object state:
// Memento Pattern
public class TextEditor
{
private string _content;
private string _fontName;
private int _fontSize;
public TextEditor()
{
_content = "";
_fontName = "Arial";
_fontSize = 12;
}
public void SetContent(string content)
{
_content = content;
}
public void SetFont(string fontName)
{
_fontName = fontName;
}
public void SetFontSize(int size)
{
_fontSize = size;
}
public IMemento CreateMemento()
{
return new TextEditorMemento(_content, _fontName, _fontSize);
}
public void Restore(IMemento memento)
{
if (memento is TextEditorMemento textMemento)
{
_content = textMemento.Content;
_fontName = textMemento.FontName;
_fontSize = textMemento.FontSize;
}
}
public void Display()
{
Console.WriteLine($"Content: {_content}");
Console.WriteLine($"Font: {_fontName}");
Console.WriteLine($"Size: {_fontSize}");
}
}
public interface IMemento
{
DateTime CreatedAt { get; }
}
public class TextEditorMemento : IMemento
{
public string Content { get; }
public string FontName { get; }
public int FontSize { get; }
public DateTime CreatedAt { get; }
public TextEditorMemento(string content, string fontName, int fontSize)
{
Content = content;
FontName = fontName;
FontSize = fontSize;
CreatedAt = DateTime.Now;
}
}
public class History
{
private readonly Stack _mementos = new Stack();
public void Push(IMemento memento)
{
_mementos.Push(memento);
}
public IMemento Pop()
{
return _mementos.Pop();
}
public bool HasMementos()
{
return _mementos.Count > 0;
}
}
// Usage
public class Program
{
public static void Main()
{
var editor = new TextEditor();
var history = new History();
// Initial state
editor.SetContent("Hello");
editor.SetFont("Arial");
editor.SetFontSize(12);
Console.WriteLine("Initial state:");
editor.Display();
// Save state
history.Push(editor.CreateMemento());
// Make changes
editor.SetContent("Hello, World!");
editor.SetFont("Times New Roman");
editor.SetFontSize(14);
Console.WriteLine("\nAfter changes:");
editor.Display();
// Save state
history.Push(editor.CreateMemento());
// Make more changes
editor.SetContent("Hello, World! How are you?");
editor.SetFont("Calibri");
editor.SetFontSize(16);
Console.WriteLine("\nAfter more changes:");
editor.Display();
// Undo changes
if (history.HasMementos())
{
editor.Restore(history.Pop());
Console.WriteLine("\nAfter first undo:");
editor.Display();
}
// Undo more changes
if (history.HasMementos())
{
editor.Restore(history.Pop());
Console.WriteLine("\nAfter second undo:");
editor.Display();
}
}
}
Best Practices & Implementation Guidelines
When to Use Patterns
- Use Singleton for global state management
- Apply Factory when object creation is complex
- Use Observer for event-driven systems
- Implement Strategy for interchangeable algorithms
Testing Strategies
- Write unit tests for pattern implementations
- Use mocking for pattern dependencies
- Test pattern interactions
- Verify pattern behavior
Code Organization
- Group patterns by category
- Use clear naming conventions
- Document pattern usage
- Maintain pattern consistency
Learning Resources
Books
-
Design Patterns: Elements of Reusable Object-Oriented Software
The classic Gang of Four book on design patterns.
-
Head First Design Patterns
An engaging introduction to design patterns.
-
Clean Code
Learn how to write clean, maintainable code.
Video Courses
-
Design Patterns in C#
Comprehensive video course with practical examples.
-
Advanced C# Design Patterns
Deep dive into modern design patterns.
-
SOLID Principles and Design Patterns
Learn how SOLID principles relate to design patterns.
Online Resources
-
Microsoft Documentation
Official C# documentation and patterns.
-
GitHub Examples
Real-world implementations of design patterns.
-
Stack Overflow
Community discussions and solutions.