In this article I will describe what a Design Pattern is. And in the Design Pattern, the use of a Strategy Pattern.

A Design Pattern is nothing but a way to organize your code in a particular style or manner. While writing code a developer may follow some organizing pattern without knowing what pattern he follows. Which means that in our absence of mind each developer follows some pattern while coding.

There are 3 types of design patterns according to Gang of Four.

Creational Pattern

Structural Patterns

Behavioral Patterns.

Today I will describe the Strategy Pattern. It is a type of behavior pattern.

A Strategy Pattern encapsulates your algorithm, or you can say the business rule, in the runtime.

Suppose you have to develop a billing rule in your application and you have different billing rules depending on your requirements.

You can write your rules and choose which one to call by using an if or a switch case. But this is not a good way to write code.

You have to follow a particular pattern or way to handle this kind of situation.

So here comes The Strategy Pattern.

Participants The classes and/or objects participating in this pattern are:

Strategy(SortStrategy)

declares an interface common to all supported algorithms. Context uses this interface to call the algorithm defined by a ConcreteStrategy.

ConcreteStrategy(QuickSort, CountElement)

implements the algorithm using the Strategy interface

Context(SortedList)

is configured with a Concrete Strategy object

maintains a reference to a Strategy object

may define an interface that lets Strategy access its data

So here The Interface comes. Interface means bridge between your applications. So by declaring Concretestratagy

As an Interface, it means we want to reuse the particular algorithm in different classes.

Context Class means it will switch your Particular algorithm according to your need.

In this Sample Example I want to create a rule or you can say Algorithm. One is to sort the name and the other is to count the name.

It is a console application. I mainly do it for understanding the basic concept.

See my code first if you want to test my code then create a console application in your Visual Studio and paste it.

He has 4 years of experience in IT Industry. He has an experience in C#, ASP.NET, SQL Server 2005, 2008, Framework designing and OOPs. Currently, he is Working with Silverlight. His keen interest is in developing MVC3 We... Read more