Click here to Skip to main content
15,888,454 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 
I understand your point. Please bear in mind that in a real scenario, the implementation could have been different, so the code would vary in the second strategy. The purpose of this article is to offer a simple demonstration. However.. lets get back to your comment. While I still see the point, I can see some other little Gremlins coming up from your code. Lets talk about architecture:

1) If I was to design it using a UML representation, it would look like your code has eliminated code duplication(DRY) but at the same time it violates The Dependency Inversion Principle. Aren't we supposed to rely on abstractions rather than concrete implementations? Which brings the next problem?

2)Violation of this principle leads to creating coupled relationships between classes. You have managed to create a strong bond between SortedDictionaryStrategy and DictionaryStrategy. If DictionaryStrategy changes, what happens to the SortedDictionaryStrategy?

2) How would you Unit Test the SortedDictonaryStrategy?

So someone, could ask: OK, so what? Does this mean that we can't use inheritance any more and we can't inherit from base classes? Yes, but I think that we should hide it in a lower-level code.

To summarize:
I understand your point, in a real example, the code between strategies would not be "almost identical". However in terms of architecture, messing up with base classes, somewhere in the chain, can really create other obstacles, especially in a scaled code base.

Thanks for your reply
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.