How to use the strategy design template in .Net

0

Design patterns are used to solve common design problems in software development and to reduce the complexities of our source code. Design patterns can be creative (related to the creation of objects), structural (related to the assembly of objects) or behavioral (related to the collaboration of objects and the separation of responsibilities).

The strategy design model is a Gang-of-Four (GoF) Design Pattern. It is a behavioral model used to define a family of algorithms and encapsulate each of them in a class. These encapsulated algorithms are then interchangeable, that is, they can vary according to different inputs, regardless of the client who uses them.

In other words, the strategy design model breaks down the implementation code into concrete classes and therefore promotes reusability. This article presents a discussion of the strategy design model and how it can be implemented in C #.

Participants in the strategy design model

The participants in a typical implementation of the strategy design model are:

  • Strategy – used to declare a common interface for all concrete strategy types. The Context takes advantage of the Strategy interface to invoke an algorithm at run time.
  • ConcreteStrategy – used to implement the algorithm declared in the Strategy interface.
  • Context – contains a reference to the Strategy instance and uses that reference to invoke the algorithm defined by a concrete strategy type.

Implement the Strategy interface in C #

So far, so good. Now that we have the concepts, let’s now implement the model. Suppose you need to design a strategy for sorting algorithms. For example, suppose you need to sort an array of integers. Sorting algorithms are plentiful, so you want to defer choosing which sorting algorithm to use. This is where the strategy design model comes into play.

The following abstract class represents the Strategy type. This class contains the declaration of the abstract Sort method.

abstract class SortStrategy
  {
    public abstract void Sort(int[] list);
  }

Concrete policy classes implement the Sort method and represent a sorting algorithm. In this example, we have considered the following sorting algorithms:

  1. Quick sort
  2. Sorting shells
  3. Bubble sorting
  4. Sort by merge
  5. Sort by heap

Implement ConcreteStrategy classes in C #

The concrete policy classes shown below extend the abstract SortStrategy class and implement the Sort method.

class QuickSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Quick Sort");
        }
    }
    class ShellSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Shell Sort");
        }
    }
    class BubbleSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Bubble Sort");
        }
    }
    class MergeSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Merge Sort");
        }
    }
    class HeapSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Heap Sort");
        }
    }

Note that I leave it to you to implement the sort algorithms in the Sort method of each of these concrete strategy classes.

Implement the Context class in C #

The Context class contains a reference to SortStrategy. It also contains two methods: the SetSortStrategy method and a Sort method. While the former is used to define the sorting strategy to be used, the latter is used to invoke the Sort method based on the chosen sorting strategy.

class Context
    {
        private const int MAX = 10;
        private int[] numbers = new int[MAX];
        private SortStrategy _sortstrategy;
        public void SetSortStrategy(SortStrategy sortstrategy)
        {
            _sortstrategy = sortstrategy;
        }
        public void Sort()
        {
            _sortstrategy.Sort(numbers);
        }
    }

And the code snippet below shows how you can create an instance of the Context class, pass a sort strategy, and call the Sort method.

static void Main(string[] args)
        {
            Context context = new Context();
            context.SetSortStrategy(new QuickSort());
            context.Sort();
            Console.Read();
        }

The full source code is given below for your reference.

using System;
namespace StrategyDesignPattern
{
    abstract class SortStrategy
    {
        public abstract void Sort(int[] list);
    }
    class QuickSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Quick Sort");
        }
    }
    class ShellSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Shell Sort");
        }
    }
    class BubbleSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Bubble Sort");
        }
    }
    class MergeSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Merge Sort");
        }
    }
    class HeapSort : SortStrategy
    {
        public override void Sort(int[] list)
        {
            Console.WriteLine("Heap Sort");
        }
    }
    class Context
    {
        private const int MAX = 10;
        private int[] numbers = new int[MAX];
        private SortStrategy _sortstrategy;
        public void SetSortStrategy(SortStrategy sortstrategy)
        {
            _sortstrategy = sortstrategy;
        }
        public void Sort()
        {
            _sortstrategy.Sort(numbers);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Context context = new Context();
            context.SetSortStrategy(new QuickSort());
            context.Sort();
            Console.Read();
        }
    }
}

When you run this program, the following text message appears in the console window:

Quick sort

As the name suggests, the strategy design template is a strategy of managing multiple ways to solve a problem. The strategy design model can be used to encapsulate different behaviors of an object and use them in different circumstances. Some typical use cases of the strategy design model include implementing sorting algorithms, implementing different file compression algorithms, implementing various types of serialization, etc.

Copyright © 2019 IDG Communications, Inc.


Source link

Share.

Leave A Reply