C#
Strategy
Learn the family of algorithms with the Strategy pattern.
Strategy pattern
Strategy groups different methods (algorithms) for one operation under the same interface. The client picks the right strategy at runtime. This replaces if/else chains with a polymorphic call.
Payment example: IPaymentStrategy declares a Pay(decimal) method. CreditCardPayment and PayPalPayment are concrete strategies. PaymentContext holds a strategy and forwards the Pay call to it.
Exercise Payment strategy with PaymentContext
Define interface IPaymentStrategy with a string Pay(decimal amount) method. CreditCardPayment and PayPalPayment return "Kart: " + amount and "PayPal: " + amount respectively. class PaymentContext holds an IPaymentStrategy, exposes SetStrategy(IPaymentStrategy), and forwards Pay(decimal) to the strategy. In Main, give the context a CreditCardPayment and print Pay(100m).
Show example solution
private IPaymentStrategy _strategy; public void SetStrategy(IPaymentStrategy s) => _strategy = s; public string Pay(decimal amount) => _strategy.Pay(amount); In Main: context.SetStrategy(new CreditCardPayment()); Console.WriteLine(context.Pay(100m));
Example solution:
using System;
interface IPaymentStrategy
{
string Pay(decimal amount);
}
class CreditCardPayment : IPaymentStrategy
{
public string Pay(decimal amount) => "Kart: " + amount;
}
class PayPalPayment : IPaymentStrategy
{
public string Pay(decimal amount) => "PayPal: " + amount;
}
class PaymentContext
{
private IPaymentStrategy _strategy;
public void SetStrategy(IPaymentStrategy strategy) => _strategy = strategy;
public string Pay(decimal amount) => _strategy.Pay(amount);
}
class Program
{
static void Main()
{
var ctx = new PaymentContext();
ctx.SetStrategy(new CreditCardPayment());
Console.WriteLine(ctx.Pay(100m));
}
}
When to use Strategy?
Strategy fits when: the same job has multiple methods, the method can change at runtime, or new methods are added often. Payment channels like card, transfer, and crypto are a good example.
Avoid it when there is only one method or the choice never changes; Strategy then becomes over-engineering. A simple if may be enough. Patterns are tools, not goals.
Test yourself
-
Declare the strategy interface
public ____ IPaymentStrategy { string Pay(decimal amount); }
Show answer
public interface IPaymentStrategy { string Pay(decimal amount); }
-
What does the Strategy pattern add over an if/else chain?
- Strategy removes inheritance
- Strategy works only with numbers
- Strategy is always faster
- It makes adding a new algorithm easier
Show answer
It makes adding a new algorithm easier — Correct. Adding a new strategy does not change existing code; only a new class is added.
-
Match Strategy parts
- Strategy
- Algorithm interface
- ConcreteStrategy
- Concrete algorithm
- Context
- Class holding the strategy
- SetStrategy
- Swaps strategy at runtime
Next lesson: Observer