Introducing the Strategy design pattern

Introducing the Strategy design pattern

Read Time : 2 Minutes

Friday, 12 May 2023

Design patterns are proven solutions to software design problems. They help improve code quality, promote reusability, and increase maintainability. We use them to save time and produce quality, extensible and flexible code. In this article, we are going to introduce the Strategy design pattern.

The Strategy design pattern is a behavioral design pattern that allows defining a set of methods that can be replaced at runtime. This pattern allows methods with different approaches to be independent of the objects they use. By using this pattern, the behavioral of objects can be changed at runtime and based on conditions.

 

The Strategy pattern consists of different components:

  • Context: An object that changes its behavior in different situations and based on existing strategies. This object always holds an instance of the executable Strategy.
  • Strategy: The interface that all strategies must implement in order to be usable by Context.
  • Concrete Strategies: classes that implement the Strategy interface and provide different implementations of an algorithm.

Below is an example of how to use the Strategy design pattern in C#:

// Context class
public class ShoppingCart
{
    private IShippingStrategy _shippingStrategy;
    public ShoppingCart(IShippingStrategy shippingStrategy)
    {
        _shippingStrategy = shippingStrategy;
    }
    public void SetShippingStrategy(IShippingStrategy shippingStrategy)
    {
        _shippingStrategy = shippingStrategy;
    }
    public double CalculateShippingCost(Order order)
    {
        return _shippingStrategy.CalculateShippingCost(order);
    }
}
// Strategy interface
public interface IShippingStrategy
{
    double CalculateShippingCost(Order order);
}
// Concrete Strategies
public class StandardShippingStrategy : IShippingStrategy
{
    public double CalculateShippingCost(Order order)
    {
        return 5.00;
    }
}
public class ExpeditedShippingStrategy : IShippingStrategy
{
    public double CalculateShippingCost(Order order)
    {
        return 10.00;
    }
}
// Client code
var cart = new ShoppingCart(new StandardShippingStrategy());
var order = new Order();
// Calculate shipping cost using the current strategy
var shippingCost = cart.CalculateShippingCost(order); // returns 5.00
// Change the strategy to expedited shipping
cart.SetShippingStrategy(new ExpeditedShippingStrategy());
// Calculate shipping cost using the new strategy
shippingCost = cart.CalculateShippingCost(order); // returns 10.00

In this example, the strategy design pattern is used to calculate purchase shipping costs. ShoppingCart class as Context, IShippingStrategy interface as Strategy and StandardShippingStrategy and ExpeditedShippingStrategy classes are concrete strategies. Client code can dynamically change the shipping strategy by calling the SetShippingStrategy method on the ShoppingCart object. Finally, by calling CalculateShippingCost, the final value changes according to the selected strategy.

The strategy design pattern is useful when there are multiple algorithms that can be used interchangeably. By encapsulating each algorithm in a separate class and implementing them using a common interface, it provides a way to change the approach at runtime without affecting the client code.

To read about other design patterns, you can use the list below. There is also a code repository on GitHub that includes all the design patterns.

design patterns

Creational:Factory Design Pattern
Builder Design Pattern
Singleton Design Pattern
Prototype Design Pattern
Abstract Factory Design Pattern
Structural:Adapter Design Pattern
Bridge Design Pattern
Composite Design Pattern
Decorator Design Pattern
Facade Design Pattern
Flyweight Design Pattern
Proxy Design Pattern
Behavioral:Chain of Responsibility Design Pattern
Command Design Pattern
Interpreter Design Pattern
Mediator Design Pattern
Memento Design Pattern
Observer Design Pattern
State Design Pattern
Strategy Design Pattern
Template Method Design Pattern
Visitor Design Pattern
Iterator Design Pattern
  • Share:
reza babakhani
Reza Babakhani

I am Reza Babakhani, a software developer. Here I write my experiences, opinions and suggestions about technology. I hope that what I write is useful for you.

Latest post

Service Mesh Simplifying Microservice Communication

In the ever-evolving landscape of software development, microservices architecture has gained considerable popularity due to its scalability, flexibility, and extensibility. However, as the number of microservices in an application increases, it becomes increasingly challenging to manage their communication and ensure that they are all properly visible. This is where Service Mesh comes into play.

The Importance of Edge Computing

Due to the speed of technological evolution, one of the concepts that has attracted a lot of attention and changes the way we interact with digital systems is edge computing.

What is event-driven architecture?

Event-driven architecture (EDA) is a software design pattern that has become increasingly popular in modern software development. In this architecture, the flow of data is determined by the occurrence of events. Unlike traditional centralized systems that are constantly checking for new status. Event-driven architecture is especially useful for systems that need to process large amounts of data in real-time.

leave a comment