Strategy Design Pattern

If you have the algorithms with conditional statements in the client code it will be messy. The Strategy pattern moves an algorithm from the client code to a separate class. A program that requires a particular service or function and that has several ways of carrying out that function is a candidate for the Strategy pattern. Programs choose between these algorithms based on computational efficiency or user choice. There can be any number of strategies, more can be added, and any of them can be changed at any time. One of the dominant strategies of object-oriented design is the “open-closed principle”.

There are a number of cases in programs where we would like to do the same thing in several different ways. Here is a list that can be strategy:

  • Compress files using different algorithms
  • Save files in different formats
  • Use different link-breaking strategies to display text data
  • Capture video data using different compression schemes
  • Plot the same data in different formats: line, graph, bar chart, or pie chart

Let’s consider a simplified sorting an array using quick sort or bubble sort which a client will choose as an algorithm to sort elements in array. Here is an example below I have to do now in both C# and JavaScript:

Code in C#

There are QucikSort and BubbleSort as concrete classes will implement an interface because they have the same method, the only different is an algorithm.

using System;

namespace Patterns.Strategy
{
    public interface ISortStrategy
    {
        void Sort(string[] arr);
    }

    public class QuickSort : ISortStrategy
    {
        public void Sort(string[] arr)
        {
            Console.Write(string.Format("QuickSort array contains {0} elements", arr.Length));
        }
    }

    public class BubleSort : ISortStrategy
    {
        public void Sort(string[] arr)
        {
            Console.Write(string.Format("BubleSort array contains {0} elements", arr.Length));
        }
    }

    public class SortableArray
    {
        private readonly ISortStrategy sortStrategy;

        public SortableArray(ISortStrategy sortStrategy)
        {
            this.sortStrategy = sortStrategy;
        }

        public void SortArray(string[] arr)
        {
            sortStrategy.Sort(arr);
        }
    }
}

Here is a client code will choose which algorithm is needed to sort an array.

using System;

namespace Patterns.Strategy
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var array = new[] {"a", "b", "c", "d", "e"};

            var sortableArray = new SortableArray(new QuickSort());
            sortableArray.SortArray(array);
            Console.Read();
        }
    }
}

Code in JavaScript

var Patterns = {};
Patterns.Strategy = {};

Patterns.Strategy.SortableArray = function(sortStrategy) {
    this.sort = function(arr) {
        sortStrategy(arr);
    };
};

Patterns.Strategy.SortStrategy = {
  quickSort : function(arr){
    console.log('QuickSort array contains ' + arr.length + ' elements');
  },

  bubbleSort : function(arr){
    console.log('BubbleSort array contains ' + arr.length + ' elements');
  }
};

var array = ["a", "b", "c", "d", "e"];
var sortableArray = new Patterns.Strategy.SortableArray(Patterns.Strategy.SortStrategy.quickSort);
sortableArray.sort(array);

If you meet this problem and need to solve it please go to your application and do the code refactorings which is now the ReSharper tool add-in to Visual Studio is very powerful to do this and much more. Doesn’t it?

No comments as yet.

Anonymous - Gravatar

No comments have yet been made to this posting.

Commentors on this Post-

Leave a Comment-

Comment Guidelines: Basic XHTML is allowed (a href, strong, em, code). All line breaks and paragraphs are automatically generated. Off-topic or inappropriate comments will be edited or deleted. Email addresses will never be published. Keep it PG-13 people!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

All fields marked with "*" are required.