Mastering the Strategy Pattern

Mastering the Strategy Pattern

We are continuing our journey through Behavioral Patterns in software design. In previous lessons, we explored the Command and Observer patterns, focusing on object communication and state changes. Now, we will learn how to implement the Strategy Pattern in C#. We will break down the pattern into manageable parts and illustrate its practical application through a clear example.

Understanding the Strategy Pattern

The Strategy Pattern is like choosing the best tool from a toolbox for a specific job. It allows a class to switch between different algorithms (strategies) seamlessly without changing its code.

Consider a scenario where you have a ShoppingCart class that needs to handle payments using different methods, like credit cards or PayPal. With the Strategy Pattern, we can encapsulate these payment methods into separate classes and let the ShoppingCart class use any of these strategies interchangeably.

The main components of the Strategy Pattern are:

  1. Strategy Interface: Defines a common interface for all strategies.
  2. Concrete Strategies: Specific classes implementing the strategies.
  3. Context Class: A class that uses the strategies.

Let's dive right in and start implementing this pattern to our payments scenario.

Strategy Interface

First, we need to define an interface that all payment strategies will implement. This ensures that all payment methods follow a common interface and can be used interchangeably.

// Define the interface for the payment strategy
interface IPaymentStrategy
{
    void Pay(int amount);
}

In this snippet, we create an interface IPaymentStrategy with a method Pay. Any class that implements IPaymentStrategy must provide an implementation of the Pay method.

Concrete Strategies: Credit Card Payment

Next, we implement concrete strategies that encapsulate different payment methods. Here, we start with the CreditCardStrategy.

// Implementation of the CreditCard strategy
class CreditCardStrategy : IPaymentStrategy
{
    private string cardNumber;

    // Constructor to initialize the card number
    public CreditCardStrategy(string cardNumber)
    {
        this.cardNumber = cardNumber;
    }

    // Implement the Pay method for CreditCard strategy
    public void Pay(int amount)
    {
        Console.WriteLine($"Paid {amount} using Credit Card: {cardNumber}");
    }
}

In the CreditCardStrategy class, we implement the Pay method to handle credit card transactions. This class requires a card number upon initialization.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal