Click here to Skip to main content
15,881,588 members
Articles / Programming Languages / C#

An Example of Strategy Design Pattern for Beginners

Rate me:
Please Sign up or sign in to vote.
3.31/5 (13 votes)
25 Oct 2010CPOL3 min read 54.7K   405   14   7
This example shows how and where to implement the strategy design pattern.

Introduction

Sometimes, we need to carry out several computations / algorithms depending on certain conditions. We go ahead in implementing those generally by applying either switch or ternary operator or if else. Though initially somehow we manage to write those programs, but if the program demands are too complex then it is difficult to frame such as well as to maintain.

Moreover, writing all the logic in a single place is not at all advisable as it yields to tight coupling.

Background

In many situations, we come across the need to write computational logic/algorithms which we generally accomplish by using if else / switch or ternary operator. It becomes difficult at times to write such a program and later on adds a lot of cost during maintenance.

Rescuer

Strategy design pattern. It comes under the category of Behavioral Patterns.

How

  1. Decouples the client and the algorithm/ computation logic in separate classes
  2. Helps to switch algorithms at any time
  3. Easily allows to plug in a new algorithm

Pattern Components

The strategy pattern comprises the following components:

  1. Strategy Interface - Interface common to all concrete strategies
  2. Concrete Strategies / Different algorithm classes - Various concrete classes that implement the strategy interface for the sake of algorithm implementation specific to itself
  3. Context Class - Delegates requests to the indicated Concrete Strategies received from the client. It does so as it keeps reference of the concrete strategies.
  4. Client - In this case, the Windows form

Case Study

Let us take the example of MSWord application. The various Font Styles (e.g. Bold, Italic, etc.) can be implemented by using this design pattern. Let us see the same as under.

Implementation of Strategy Interface

The IFontStyle interface looks as below:

C#
public interface IFontStyle
{
   public Font GetNewFontStyle(Control c);
}

Implementation of Concrete Strategies

There are four concrete strategy classes, viz Bold.cs, Italic.cs, Underline.cs and StrikeThru.cs.

Since all follows the same pattern in this example, so for the sake of simplicity I am describing only for the Bold concrete class.

It goes as below:

C#
public class Bold : IFontStyle
{
        #region IFontStyle Members

        public Font GetNewFontStyle(System.Windows.Forms.Control c)
        {
            return new Font(c.Font, FontStyle.Bold);
        }

        #endregion
}

The code is self explanatory. The Bold class implemented the strategy interface IFontStyle where it is returning the font style as bold.

Implementation of Context

The FontStyleContext class is as under:

C#
public class FontStyleContext
{
        //step 1: Create an object of Strategy Interface
        IFontStyle _IFontStyle;

        //step 2:Set the concrete call called by the client to the 
        //interface object defined in the step 1
        public FontStyleContext(IFontStyle IFontStyle)
        {
            this._IFontStyle = IFontStyle;
        }

        //step 3: A method that will return the font style
        public Font GetFontStyle(Control c)
        {
            return _IFontStyle.GetNewFontStyle(c);
        }
}

Implementation of Client

The client design is as under:

1.JPG

And the code behind for the Bold Button click is as under:

C#
// Bold Click
private void btnBold_Click(object sender, EventArgs e)
{
  objFontStyleContext = new FontStyleContext(new Bold());
  richTextArea.Font =  objFontStyleContext.GetFontStyle(richTextArea);           
}

First, we have created an instance of the FontStyleContext class and then instantiated the same with the appropriate StrategyConcrete class. Next by calling the GetFontStyle method, we were able to set the appropriate Font style for the richtextbox.

The other buttons will have the same implementation with only call to appropriate concrete classes.

Output

2.jpg

Resource

Conclusion

Strategy pattern is of great importance while implementing program logic that will be invoked depending on conditions. This is just a simple example to demonstrate the pattern idea. In real time, we will be adorned with more complex situations but the underlying concept will be the same.

Comments are highly appreciated for the improvement of the topic.

Thanks for reading the article.

History

  • 26th October, 2010: Initial post

License

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



Comments and Discussions

 
GeneralMy vote of 1 Pin
inf1n1te28-Sep-11 8:18
professionalinf1n1te28-Sep-11 8:18 
GeneralMy vote of 4 Pin
haxy1234-Jan-11 17:06
haxy1234-Jan-11 17:06 
GeneralMy vote of 1 Pin
Batzen28-Oct-10 1:59
Batzen28-Oct-10 1:59 
GeneralMy vote of 1 Pin
JF201526-Oct-10 18:09
JF201526-Oct-10 18:09 
GeneralRe: My vote of 1 Pin
Niladri_Biswas26-Oct-10 18:44
Niladri_Biswas26-Oct-10 18:44 
GeneralMy vote of 1 PinPopular
ashved26-Oct-10 7:42
ashved26-Oct-10 7:42 
GeneralRe: My vote of 1 Pin
Niladri_Biswas26-Oct-10 16:57
Niladri_Biswas26-Oct-10 16:57 

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.