The strategy pattern is typically used when your programmer's algorithm should be interchangeable with different variations of the algorithm. For example, if you have code that sorts array, under certain circumstances, you might want to create QuickSort and under other circumstances, you might want to create Merge Sort.

The strategy pattern is usually implemented by declaring an abstract base class with an algorithm method, which is then implemented by inheriting concrete classes. At some point in the code, it is decided what concrete strategy is relevant; it would then be instantiated and used wherever relevant.

Following example shows how a ArrayList with diffrent sort algorithms.


using System;
using System.Collections;
using NUnit.Framework;

namespace DesignPatterns
{
    // Strategy class: SortStrategy
    // Define the general interface common to all supported algorithms
    public abstract class SortStrategy
    {
        public abstract void Sort(ArrayList list);
    }

    // Concrete class QuickSort
    public class QuickSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            // Sort the list using a quicksort algorithm
        }
    }

    // Concrete class MergeSort
    public class MergeSort : SortStrategy
    {
        public override void Sort(ArrayList list)
        {
            // Sort the list using a mergesort algorithm
        }
    }

    // Context class
    public class SortedList
    {
        private ArrayList list = new ArrayList();
        private SortStrategy sortstrategy;

 public SortedList(SortStrategy sortstrategy)
        {
            this.sortstrategy = sortstrategy;)
   
 }
       
        public void Add(string name)
        {
            list.Add(name);
        }

        public void Sort()
        {
            sortstrategy.Sort(list);
        }
    }

    [TestFixture]
    public class StrategyClassTestFixture
    {
        [Test]
        public void TestSortedList()
        {
            SortedList sortedList = new SortedList(new QuickSort());

            sortedList.Add("mitchel");
            sortedList.Add("gregg");
            sortedList.Add("steve");
            sortedList.Add("rob");

        }
    }
}

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

since i have already posted basic ContraVariance in delegate, i am not going to go thru the same again, those of you who had missed my earlier post can refer here

here is an example of using generics with contravariance

namespace ContravarianceWithGenerics
{
    public interface IEquity
    {
        string ToString();
        string Save();
    }

    //base class
    abstract class Equity : IEquity
    {
        int _price;

        public Equity(int Price)
        {
            _price = Price;
        }
        public override string ToString()
        {
            return GetType().Name + " : " + _price;
        }

        #region IEquity Members


        public virtual string Save()
        {
            return "Called from Base Class";
        }

        #endregion
    }
    //derived
    class Stock : Equity
    {
        public Stock(int Price)
            : base(Price)
        {

        }

        public override string Save()
        {
            return "Called from Stock Class";
        }
    }

    //derived
    class Bond : Equity
    {
        public Bond(int Price)
            : base(Price)
        {

        }

        public override string Save()
        {
            return "Called from Bond Class";
        }
    }

    class EquityBusinessImplementation<T> where T: Equity, IEquity
    {
        public delegate void SellNotify(T b);

        public void EquitySaleReport(Equity e)
        {
            Console.WriteLine("Report of sale is " + e);
            Console.WriteLine(e.Save() );
        }
        public SellNotify sellNotifyDlg;

        public void Sell(T s)
        {
            if (null != sellNotifyDlg)
            {
                sellNotifyDlg(s);
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            EquityBusinessImplementation<Stock> s =
                new EquityBusinessImplementation<Stock>();
            s.sellNotifyDlg += s.EquitySaleReport;
            s.Sell(new Stock(100));

            EquityBusinessImplementation<Bond> b =
                new EquityBusinessImplementation<Bond>();
            b.sellNotifyDlg += b.EquitySaleReport;
            b.Sell(new Bond(1000));
        }
    }
}

Happy programming !!!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati