Strategy Design Pattern in Visual Basic .NET

Definition

Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it

In this pattern you have several algorithms to do a task. Depending on your requirement you can select the algorithm dynamically. You can implement each algorithm in separate class

This is the UML diagram for Strategy Design Pattern

Participants

Strategy
This is an interface which your algorithm (ConcreteStrategy) uses to implement it

ConcreteStrategy
Implements the algorithm using the Strategy interface.
Context
Context is configured with a ConcreteStrategy object to make dynamic call
Maintains a reference to a Strategy object.

Strategy Design Pattern example in VB.NET

I will do simple example to show you how to implement this Strategy design pattern in VB.NET. We will first create list of student and try to sort this list using different type of sorting algorithms

Our Strategy here is the Sorting. I am going to select three algorithms for sorting named Merge Sort, Bubble Sort, Quick Sort. So those sorting methods are my Concrete Classes. Now lets look at the UML diagram for this example

StudentList class is our Context Class. This class has reference to SortStrategy interface and maintain the list of student for strategy.

Our Strategy interface is the SortStrategy interface which has the Sort method

Then we have three ConcreteStrategy classes named QuickSort,BubbleSort and MergeSort. They implement the SortStrategy interface

QuickSort Class

BubbleSort Class

MerrgeSort Class

In the Client section , I have written the following code to test above Strategy Design Pattern. This will add several student to the List and do the sorting operations

Now you will get the following output

Leave a Reply

Your email address will not be published. Required fields are marked *