Skip to main content

How to Implement the Strategy Pattern in Csharp

The Strategy pattern is a behavioral design pattern that helps you define a family of algorithms and make them interchangeable. Instead of hardcoding algorithms into classes, the Strategy pattern enables them to be selected at runtime. This pattern is particularly useful for promoting flexibility and adhering to SOLID principles like the Open/Closed Principle. But how can you effectively implement it in C#? This guide breaks it down step by step.

What is the Strategy Pattern?

In simple terms, the Strategy pattern allows you to switch between different methods or algorithms without modifying the client code. Think of it as selecting tools from a toolbox—you choose the appropriate one based on what you need to do. It separates the algorithm logic from the client, making your code easier to maintain and expand.

Suppose you’re building a payment system. Customers can choose how they want to pay: credit card, bank transfer, or cryptocurrency. By applying the Strategy pattern, you can define these payment options as separate algorithms and switch between them as needed.

Why Use the Strategy Pattern in C#?

C# is an object-oriented language ideal for applying design patterns. The Strategy pattern offers several benefits:

  1. Promotes Code Reusability: Write once, reuse in multiple contexts.
  2. Eases Maintenance: Modify or add new algorithms without touching existing code.
  3. Enhances Flexibility: Decouple algorithms and client code.

How the Strategy Pattern Works in C#

The Structure of the Strategy pattern generally includes:

  1. Context: The part of your code that uses the Strategy.
  2. Strategy Interface: Defines a common interface for all supported strategies.
  3. Concrete Strategies: Implementations of the Strategy interface representing the algorithms.
  4. Client Code: The consumer that interacts with the context.

Now let’s jump into practical implementation.


Step-by-Step Implementation of the Strategy Pattern in C#

Step 1: Define the Strategy Interface

Start by defining a simple interface that all strategies will implement.

public interface IPaymentStrategy
{
    void Pay(decimal amount);
}

Step 2: Implement Concrete Strategies

Provide different algorithms that conform to the IPaymentStrategy interface.

public class CreditCardPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount:C} using Credit Card.");
    }
}

public class BankTransferPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount:C} using Bank Transfer.");
    }
}

public class CryptoPayment : IPaymentStrategy
{
    public void Pay(decimal amount)
    {
        Console.WriteLine($"Paid {amount:C} using Cryptocurrency.");
    }
}

Step 3: Create the Context Class

The context will use a strategy to perform its operations. You can change the strategy at runtime.

public class PaymentContext
{
    private IPaymentStrategy _paymentStrategy;

    public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)
    {
        _paymentStrategy = paymentStrategy;
    }

    public void ExecutePayment(decimal amount)
    {
        if (_paymentStrategy == null)
        {
            Console.WriteLine("Payment strategy is not set.");
            return;
        }

        _paymentStrategy.Pay(amount);
    }
}

Step 4: Client Code Example

Here’s how you can switch strategies dynamically:

class Program
{
    static void Main(string[] args)
    {
        PaymentContext context = new PaymentContext();

        Console.WriteLine("Choose payment method: 1. Credit Card, 2. Bank Transfer, 3. Crypto");
        string choice = Console.ReadLine();

        switch (choice)
        {
            case "1":
                context.SetPaymentStrategy(new CreditCardPayment());
                break;
            case "2":
                context.SetPaymentStrategy(new BankTransferPayment());
                break;
            case "3":
                context.SetPaymentStrategy(new CryptoPayment());
                break;
            default:
                Console.WriteLine("Invalid choice.");
                return;
        }

        context.ExecutePayment(100.00m);
    }
}

Explanation of the Code

  1. Strategy Interface: Defines the Pay method, which each payment strategy must implement.
  2. Concrete Strategies: Implements specific payment methods like credit card or bank transfer.
  3. Context Class: Acts as the environment to switch between strategies at runtime.
  4. Client Code: Allows the user to choose and execute a payment strategy.

Advantages of Using the Strategy Pattern

  • Extensibility: Add new strategies without affecting existing code.
  • Testability: Test each algorithm separately.
  • Decoupling: Context doesn’t worry about how a task is executed.

Conclusion

Using the Strategy pattern in C# makes your code maintainable, scalable, and flexible. It’s an excellent choice for scenarios where an object’s behavior can change dynamically, such as a payment system or sorting algorithms.

Want to dig deeper into more design patterns? Check out https://www.javathecode.com/design-patterns-in-csharp to explore other patterns and enhance your C# skills. Try implementing the Strategy pattern in your own projects to truly understand its power. Your code (and your future self) will thank you! Happy coding!

Popular posts from this blog

How to Check if Someone is Connected to Your Machine in Linux

Picture this: you glance at your system monitor and notice your CPU is humming along even though you're not running anything demanding. Or maybe your internet feels sluggish for no obvious reason. A small, uneasy thought creeps in — is someone else on my machine right now? For Linux users, this isn't something you have to wonder about. Linux ships with a powerful set of built-in tools that let you see exactly who's connected, who's logged in, and what your network is doing at any given moment. You don't need to be a security expert to use them — you just need to know where to look. This guide walks you through the practical, no-nonsense steps to check for unauthorized connections on your Linux system, with real commands you can run right now. Why Monitoring Network Connections Matters Every device on a network — including your own Linux machine — communicates using an IP address. When another device or user connects to your system, that connection shows up as a trac...

How to Set Up a Linux Web Server and Host an HTML Page Easily

Setting up a web server on Linux means spending a fair amount of time in the terminal — Linux leans heavily on the command line rather than clicking through menus, so you'll be typing out instructions more often than not.  If you're new to this, it can feel a little intimidating at first, but the good news is you don't need to become a Linux wizard overnight. A handful of core commands will get you surprisingly far. A few you'll lean on constantly: cd — move between directories ls — see what's in the current directory mkdir — create a new folder nano or vim — edit files right there in the terminal sudo — run something with administrator privileges Get comfortable with these and you'll be able to navigate around, tweak configuration files, and install software without much trouble. You don't need to memorize everything — you just need to be confident enough to follow along with clear instructions, which is exactly what this guide aims to give you....

Linux Network Troubleshooting

If you've spent any time as a sysadmin — or honestly, just as someone who's had to fix their own home network at 11pm — you know that connectivity issues are one of the most common headaches out there. The good news is that a handful of core tools and a methodical approach can take you from "why isn't this working" to a root cause pretty quickly.  This guide walks through the essentials: configuring interfaces, managing routes, and diagnosing problems when things go sideways. Configuring Network Interfaces Your network interfaces are the actual bridge between your machine and the outside world, so getting them configured correctly is step one for any kind of reliable connectivity. Doing It Manually ifconfig is the old-school, tried-and-true tool for this on Unix-like systems. To see everything currently configured, run: ifconfig -a If you need to manually set up a specific interface — assigning an IP, a netmask, and bringing it online — it looks like this: ifconf...