Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#5.0

Strategy Design Pattern (C#)

4.05/5 (6 votes)
12 Feb 2015CPOL 30.5K   195  
A console application that calculates word occurrences found in a text.

Image 1

Introduction

This tip demonstrates the usage of strategy design pattern. We display two different implementations of IDictionary<K,T> based on Strategy.

Background

Image 2

Strategy is a behavioral design pattern that involves removing an algorithm from its host class and putting it in a separate class. There may be different algorithms (strategies) that are applicable for a given problem. If the algorithms are all kept in the host, messy code with lots of conditional statements will result. The Strategy pattern enables a client to choose which algorithm to use from a family of algorithms and gives it a simple way to access it.

Using the Code

Our family of algorithms, in our current example, is two different implementations of IDictionary<K,T>. First Algorithm will return a simple Dictionary<K,T>, whereas the second one will return a SortedDictionary<K,T>.

C#
 public interface IDictionaryStrategy
 {
        IDictionary<string, int> GetProcessedText(string text);
 }

 public class DictionaryStrategy : IDictionaryStrategy
 {
        public IDictionary<string, int> GetProcessedText(string text)
        {
            string[] words = text.Split(' ', ';', ',', '.');

            var dictionary = new Dictionary<string, int>();
            int count = 1;

            foreach (var item in words.Where(x => x != string.Empty))
            {
                int value=0;
                if(!dictionary.TryGetValue(item,out value))
                {
                    count = 0;
                }
                dictionary[item] = ++count;
            }

            return dictionary;
        }
 }

public class SortedDictionaryStrategy : IDictionaryStrategy
{
        public IDictionary<string, int> GetProcessedText(string text)
        {
            string[] words = text.Split(' ', ';', ',', '.');
            
            var dictionary = new SortedDictionary<string, int>(new CaseInsensitiveComparer());

            int count = 1;

            foreach (var item in words.Where(x=>x!=string.Empty))
            {
                int value = 0;
                if (!dictionary.TryGetValue(item, out value))
                {
                    count = 0;
                }
                dictionary[item] = ++count;
            }

            return dictionary;
        }

        class CaseInsensitiveComparer : IComparer<string>
        {
            public int Compare(string s1, string s2)
            {
                return string.Compare(s1, s2, true);
            }
        }
 }

Points of Interest

Big fan of GoF!

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)