Wednesday, April 21, 2010

Strategy Design Pattern By Example in C#

This is part of a series of posts in which we will deal with some of the popular design patters using simple but non-trivial examples.

Strategy Pattern delivers similar functionality as the Template Pattern. But the implementation is different. So we will use the same sample scenario as we did for the Template Pattern.

Our task here is to import data into our system from multiple source types. The task of checking for duplication and adding to our repository is common functionality. Whereas reading and converting the incoming data to our format would be different for each kind of datasource. In this example we will import Xml and CSV data into our repository.

The Strategy Pattern involves two parts. The Interface which defines all the varying functionality and  a Class with all the common functionality   The class also takes in the implementation of the Interface in its constructor.

Enough theory, Lets dive into our sample implementation and check out the actors.  The download link to this sample is available at the bottom.

  • IImportData Interface is the interface which defines the functionality which with each kind of data we will be importing.
  • ImportDataHandler Class takes in an implementation of IImportData Interface as a parameter in its constructor.  This class also has other common functionality like checking for duplicates and add data to the repository.

  • ImportCSVData Class & ImportXmlData Class are implementations of the IImportData Interface.  
So importing csv and xml data into our repository is simply a matter of passing in the required implementation to the ImportDataHandler class and calling its Execute method.


So if the Strategy and Template Patter offer similar functionality, which one to use? The answer is it depends.  We will leave that for a later post.

Download Sample Code

Happy Coding

Ravi