Wednesday, September 9, 2009

Strategy Pattern with C#

Strategy Pattern classified under Behavioural Pattern encapsulates an algorithm inside a class.

Strategy Pattern is a class that has to perform strategically depending on user input, platform information and so on.. Depending on user input, a different algorithm will be used; however, the end result is the same.

To explain this through example, I have used three diferrent search algorighm, each with its own performance and accuracy trade-off. One of them is very computation-intensive, but does a more thorough job, while another is faster but generates results that may be inaccurate for very data. My application will ask the user for the desired performance and then invoke the appropriate algorithm. To this end, I will encapsulate my algorithms in classes that demonstrate Strategy Pattern.

iSearch.cs
This interface will be implemented by various classes with different search algorithm


namespace MyProject.StrategyPattern.Search
{
public interface iSearch
{
string Search(string keyword);
}
}



Search.cs
Having implemented all three algorithms in this manner mentioned below, I can now design the client that decouples it from the implementation details of any specific algorithm. The client holds a reference to the interface, and does not need to know anything about the concrete implementation of the interface.


namespace MyProject.StrategyPattern.Search
{

public class ListSearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + "with List Search Algorithm";
}

#endregion
}


public class TreeSearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + " with Tree Search Algorithm";
}

#endregion
}


public class BinarySearch : iSearch
{
#region iSearch Members

public string Search(string keyword)
{
return "Searched " + keyword + " Binary Search Algorithm";
}

#endregion
}

}


SearchKeyword.cs
Finally, I create an instance of the SearchKeyword class and, depending on user input, initialize it with the appropriate algorithm. The Test method of the SearchKeyword class invokes the Search method of the iSearch interface that every algorithm implements

namespace MyProject.StrategyPattern
{
public class SearchKeyword
{
private iSearch _search;

public SearchKeyword(iSearch Search)
{
_search = Search;
}

public string SearchString(string Keyword)
{
return _search.Search(Keyword);
}


}
}



< Back to Design Patterns

No comments:

Post a Comment