Click here to Skip to main content
15,887,822 members
Articles / Programming Languages / C# 5.0
Tip/Trick

Strategy Design Pattern (C#)

Rate me:
Please Sign up or sign in to vote.
4.05/5 (6 votes)
12 Feb 2015CPOL 29.4K   193   10   14
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)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralAvoid code duplication by using a base class Pin
htschirner18-Feb-15 12:09
htschirner18-Feb-15 12:09 
GeneralRe: Avoid code duplication by using a base class Pin
Veronica S. Zotali19-Feb-15 9:06
Veronica S. Zotali19-Feb-15 9:06 
GeneralMy vote of 2 Pin
João Matos Silva14-Feb-15 11:58
professionalJoão Matos Silva14-Feb-15 11:58 
GeneralRe: My vote of 2 Pin
Veronica S. Zotali14-Feb-15 12:44
Veronica S. Zotali14-Feb-15 12:44 
Questionthanks Pin
Southmountain13-Feb-15 6:16
Southmountain13-Feb-15 6:16 
GeneralDoesn't actually illustrate or discuss the strategy part of the pattern Pin
John Brett12-Feb-15 23:58
John Brett12-Feb-15 23:58 
GeneralRe: Doesn't actually illustrate or discuss the strategy part of the pattern Pin
Veronica S. Zotali13-Feb-15 0:19
Veronica S. Zotali13-Feb-15 0:19 
GeneralRe: Doesn't actually illustrate or discuss the strategy part of the pattern Pin
_GP18-Feb-15 0:11
_GP18-Feb-15 0:11 
GeneralRe: Doesn't actually illustrate or discuss the strategy part of the pattern Pin
Veronica S. Zotali18-Feb-15 2:51
Veronica S. Zotali18-Feb-15 2:51 
QuestionLooks interesting Pin
GuyThiebaut12-Feb-15 23:10
professionalGuyThiebaut12-Feb-15 23:10 
AnswerRe: Looks interesting Pin
Veronica S. Zotali12-Feb-15 23:25
Veronica S. Zotali12-Feb-15 23:25 
GeneralRe: Looks interesting Pin
GuyThiebaut12-Feb-15 23:34
professionalGuyThiebaut12-Feb-15 23:34 
Questionthanks Pin
Member 1144952212-Feb-15 22:40
professionalMember 1144952212-Feb-15 22:40 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.