Thursday, May 2, 2013

Published 1:50 AM by with 0 comment

Strategy Pattern - [Behavioral Patterns]



Strategy Pattern


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

So to understand these concepts, let us work on a toy application for converting audio files into different formats (like MP3 to WMA). Here the user will have an option of selecting the source file and then deciding the target output type format. The operation that will be performed is to convert the source file to the target output format.

The multiple strategies that we will be using are to define the quality of the output. The user could choose to convert to a low quality output (perhaps because it is fast and is of small size). The user could choose to convert to a high quality output (perhaps because he wants to use it on high-end audio products from BOSE or B&O), or he could just choose an average quality output (perhaps to put it on his cell phone). We implement all these as separate strategies so that the client code can be independent of the implementation details of these different strategies and will work in the same fashion for any selected strategy.

interface IStrategy
{
  void Convert();
}


class FileConverter
{
int quality;
        public FileConverter(int qual)
        {
            quality = qual;
        }

        public void FileConvert()
        {
            if (quality < 100)
            {
                Console.WriteLine("Low Quality");
            }
            else if (quality > 100 && quality < 200)
            {
                Console.WriteLine("Medium Quality ");
            }
            else
            {
                Console.WriteLine("High Quality");
            }
        }
    }


    class LowQualityConversion:IStrategy
    {
        const int QUALITY = 50;
        public void Convert()
        {
            FileConverter fcon = new FileConverter(QUALITY);
            fcon.FileConvert();
        }
    }
    class MediumQualityConversion : IStrategy
    {
        const int QUALITY = 150;
        public void Convert()
        {
            FileConverter fcon = new FileConverter(QUALITY);
            fcon.FileConvert();
        }
    }
    class HighQualityConversion : IStrategy
    {
        const int QUALITY = 250;
        public void Convert()
        {
            FileConverter fcon = new FileConverter(QUALITY);
            fcon.FileConvert();
        }
    }

Calling…

IStrategy selectStratergy = null;
int choice = Console.Read();

if (choice == '1')
{
selectStratergy = new LowQualityConversion();
}
else if (choice == '2')
{
selectStratergy = new MediumQualityConversion();
}
else if (choice == '3')
{
selectStratergy = new HighQualityConversion();
}
if (selectStratergy != null)
{
selectStratergy.Convert();
}

    email this       edit

0 comments: