Strategy - Behavioural
Overview:
The Strategy Pattern in C# transforms your code into a tactical chameleon—shifting strategies dynamically. Let's unveil the secrets behind this versatile coding strategy:
Implementation in C#:
In C#, the Strategy Pattern involves defining a family of algorithms, encapsulating each one, and making them interchangeable. Consider a payment processing scenario:
// Context (Payment Processor)
public class PaymentProcessor
{
private IPaymentStrategy paymentStrategy;
public PaymentProcessor(IPaymentStrategy strategy)
{
paymentStrategy = strategy;
}
public void SetPaymentStrategy(IPaymentStrategy strategy)
{
paymentStrategy = strategy;
}
public void ProcessPayment()
{
paymentStrategy.ProcessPayment();
}
}
// Strategy Interface
public interface IPaymentStrategy
{
void ProcessPayment();
}
// Concrete Strategies
public class CreditCardPayment : IPaymentStrategy
{
public void ProcessPayment()
{
// Process payment using credit card strategy
}
}
public class PayPalPayment : IPaymentStrategy
{
public void ProcessPayment()
{
// Process payment using PayPal strategy
}
}
Pros:
-
Clean Code: Encapsulates algorithms in separate classes, improving code organization.
-
Dynamic Behavior: Allows objects to switch strategies at runtime.
-
Open/Closed Principle: Supports adding new strategies without modifying existing code.
Cons:
-
Increased Classes: Introducing numerous strategies may lead to class proliferation.
-
Client Knowledge: Clients need to be aware of different strategies.
When to Use and When Not:
-
Use: When algorithms need to vary independently from clients or when a class has multiple behaviors and the correct one must be selected dynamically.
-
Avoid: In simpler scenarios where conditional logic suffices or when the number of strategies may lead to class explosion.
Usage in .NET Core Framework:
The Strategy Pattern is deeply ingrained in the .NET Core framework, especially in areas such as sorting and comparison algorithms. The List.Sort method, for instance, can accept custom strategies for sorting.
Real-Life Example:
Consider a document editor where users can choose different text formatting strategies. The Strategy Pattern is applied:
// Document editor context
var documentEditor = new DocumentEditor();
// Formatting strategies
var boldStrategy = new BoldTextStrategy();
var italicStrategy = new ItalicTextStrategy();
// Set initial strategy
documentEditor.SetFormattingStrategy(boldStrategy);
// Apply strategy to format text
documentEditor.FormatText(); // Outputs: Formatting text in bold
// Switch to italic strategy dynamically
documentEditor.SetFormattingStrategy(italicStrategy);
documentEditor.FormatText(); // Outputs: Formatting text in italic
No files yet, migration hasn't completed yet!