Design patterns are used to solve common design problems in software development and to reduce the complexities in our source code. Design patterns can be creational (related to object creation), structural (related to object assembly), or behavioral (related to object collaboration and separation of responsibilities).
The strategy design pattern is a Gang-of-Four (GoF) design pattern. It is a behavioral pattern used to define a family of algorithms and encapsulate each of them inside a class. These encapsulated algorithms are then interchangeable — i.e., they can vary based on different inputs, independently of the client that uses them.
In other words, the strategy design pattern decomposes implementation code into concrete classes and hence promotes reusability. This article presents a discussion of the strategy design pattern and how it can be implemented in C#.
Strategy design pattern participants
The participants in a typical implementation of the strategy design pattern include the following:
- Strategy — used to declare a common interface for all concrete strategy types. The Context takes advantage of the Strategy interface to invoke an algorithm at runtime.
- ConcreteStrategy — used to implement the algorithm that is declared in the Strategy interface.
- Context — contains a reference to the Strategy instance and uses this reference to invoke the algorithm that is defined by a concrete strategy type.