Design patterns in C# – part 13 (Strategy pattern)

Role

The Strategy pattern involves removing an algorithm from its host class and putting it in a separate class.

Design

StrategyPattern

Implementation

  • Client -> TestStrategyPattern
  • IStrategy -> IConsole
  • StrategyA, StrategyB -> PythonConsole, PowershellConsole
using System;

namespace StrategyPattern
{
    public class TestStrategyPattern
    {
        public static void Main(string[] args)
        {
            var context = new ConsoleContext();

            Console.WriteLine(context.Eval("Write-Output \"Hello World!\""));
            context.SwitchConsole();
            Console.WriteLine(context.Eval("print \"Hello World!\""));
        }
    }

    public class ConsoleContext
    {
        private IConsole _console = new PowershellConsole();

        public string Eval(string script)
        {
            return this._console.InvokeScript(script);
        }

        public void SwitchConsole()
        {
            if (this._console is PowershellConsole)
            {
                this._console = new PythonConsole();
            }
            else
            {
                this._console = new PowershellConsole();
            }
        }
    }

    public class PythonConsole : IConsole
    {
        #region IConsole Members

        public string InvokeScript(string script)
        {
            return String.Format("Python engine - evaluate script \n\t{0}", script);
        }

        #endregion
    }

    public class PowershellConsole : IConsole
    {
        #region IConsole Members

        public string InvokeScript(string script)
        {
            return String.Format("Powershell engine - evaluate script \n\t{0}", script);
        }

        #endregion
    }

    public interface IConsole
    {
        string InvokeScript(string script);
    }
}

OUTPUT:

Powershell engine – evaluate script
Write-Output “Hello World!”
Python engine – evaluate script
print “Hello World!”

Use when

  • Many related classes differ only in their behavior.
  • There are different algorithms for a given purpose, and the selection criteria can be codified.
  • The algorithm uses data to which the client should not have access.

Bibliography

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s