Design patterns in C# – part 14 (State pattern)

Role

When the state inside an object changes, it can change its behavior by switching to a set of different operations. This is a achieved by an object variable changing its subclass, within a hierarchy.

Design

StatePattern

Implementation

  • Context -> ConsoleContext
  • IState -> IConsole
  • StateB, StateA -> PowershellConsole, PythonConsole
using System;

namespace StatePattern
{
    public class TestStatePattern
    {
        public static void Main(string[] args)
        {
            var context = new ConsoleContext {State = new PowershellConsole()};

            Console.WriteLine(context.Eval("Write-Output \"Hello World!\""));
            context.State = new PythonConsole();
            Console.WriteLine(context.Eval("print \"Hello World!\""));
        }
    }

    public class ConsoleContext
    {
        public IConsole State { get; set; }

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

    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

You have objects that:

  • Will change their behavior at runtime, based on some context
  • Are becoming complex, with many conditional branches

You want to:

  • Vary the set of handlers for an object request dynamically
  • Retain flexibility in assigning request to handlers

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