KnowDotNet

Design Patterns - The Strategy Pattern

Practical Design Patterns - Strategy Pattern

by Les Smith

This is the third article in a series of articles on Design Patterns.  The last article was on the Facade Pattern.

Many times we may be using Design Patterns without knowing that we are using a pattern and certainly without knowing what the particular pattern is called.  This was the case for me five or six years ago when I wrote
NetRefactor.  In that add-in, I had to process both C# and VB.NET code.  Since I needed to perform the same function on the two different types of code, I wrote an Interface with numerous methods in it and then wrote a very large file with the classes for both sets of methods in the same file.  Admittedly, I had never studied Design Patterns and therefore did not know that I was actually using a Strategy Pattern.  But, the point is that the Strategy Design Pattern can be implemented with an interface and I basically was using the pattern in a not quite so clean way, and I did not know that it was a Design Pattern.

The objective of the Strategy Design Pattern is to define a set of algorithms, encapusulate the algorithms into concrete classes of methods, and make them interchangeable to the user of the classes. This decouples the user completely from the implementation of the classes.  The Strategy Design Pattern can be implemented more than one way.  It can be done with a Interface or an abstract (MustInherit in VB.NET) class.  In this article I am going to use an abstract class.  The UML diagram shown below shows the components involved in the pattern.

Strategy


Now I will show the following components in code.  First, I will define them.