The Strategy Pattern Example in C#

The Strategy Pattern is a proven design construct to vary operations or algorithms independently from the clients that use it. The pattern underwrites the Open / Closed Principle of S.O.L.I.D., stating that a class should be open to extension, but closed to modification. It also keeps a clean separation of concerns.

Lets say we go to our local car wash. We buy a car washing program at the store. We then drive our car inside the washing machine where it starts to execute the washing program. When we apply the Strategy Pattern to this model, we come up with something like shown below.

First we create a washing program strategy interface. We implement the interface to express our different washing programs. In this case we have to flavors; Basic and Deluxe. For simplicity the strategy ‘algorithm’ Wash() only writes a program process description to the console window. Normally we would find fancy calculations of some sort here.

using System;
 
namespace StrategyPattern
{
    public interface ICarWashStrategy
    {
        void Wash(Car car);
    }
 
    public class BasicProgram : ICarWashStrategy
    {
        #region ICarWashStrategy Members
 
        public void Wash(Car car)
        {
            Console.WriteLine(
                "** Starting Basic Program on {0} **",
                car.Name);
            Console.WriteLine("Water");
            Console.WriteLine("Soap");
            Console.WriteLine("Clean");
            Console.WriteLine("Dry");
            Console.WriteLine("** DONE **");
        }
 
        #endregion
    }
 
    public class DeluxeProgram : ICarWashStrategy
    {
        #region ICarWashStrategy Members
 
        public void Wash(Car car)
        {
            Console.WriteLine(
                "** Starting Deluxe Program on {0} **", 
                car.Name);
            Console.WriteLine("Pre Wash");
            Console.WriteLine("Adding a lot of Water");
            Console.WriteLine("Spraying Hot Soap");
            Console.WriteLine("Tire Brush");
            Console.WriteLine("Wrap-Around Washers");
            Console.WriteLine("Rinse and Wax");
            Console.WriteLine("Soft Dry");
            Console.WriteLine("** DONE **");
        }
 
        #endregion
    }
}

The CarWashService takes the washing program (the strategy) we have bought at the shop and initializes the washing machine with it.

namespace StrategyPattern
{
    internal class CarWashService
    {
        private readonly ICarWashStrategy _carWashStrategy;
 
        public CarWashService(ICarWashStrategy carWashStrategy)
        {
            _carWashStrategy = carWashStrategy;
        }
 
        public void Wash(Car car)
        {
            _carWashStrategy.Wash(car);
        }
    }
}

Using the CarWasService in an application should be pretty straight forward. We drive in our Opel Manta and start the washing operation by calling the Wash() method.

using System;
 
namespace StrategyPattern
{
    internal class Program
    {
        private static void Main()
        {
            var car = new Car { Name = "Opel Manta" };
            var washProgramStrategy = new DeluxeProgram();
            var carWash = new CarWashService(washProgramStrategy);
 
            carWash.Wash(car);
 
            Console.ReadLine();
        }
    }
}

Strategy Pattern Console

We can apply any washing program to the CarWashService we want. If new Washing Programs are added later, we don’t have to modify the CarWashService.

10 thoughts on “The Strategy Pattern Example in C#

  1. Hoi Leon,
    Toevallig heb ik vorige week ook eens wat artikelen geleze over SOLID. Het ziet er erg interessant uit. Maar sommige zaken zijn erg complex en begrijp ik het nut nog niet helemaal van. Maar van de S van single responsibility, daar zie ik absoluut het nut wel van in. Die wil ik bij Telfort Zakelijk ook gaan introduceren. Help je mee?…
    Gr., Marco

  2. Hey Marco V.

    Dit weekend staat S.O.L.I.D. bij mij op het programma – naast WCF cramming ;-)

    Ik wilde eigenlijk eerst graag wat meer weten over IoC frameworks als Unity en Windsor, maar zag al snel dat ik wat basis mis. Ik wandel nu nog wat rond in al die principles en design patterns. Zie soms door de interfaces het bos niet meer.

    Ik ga ze in ieder geval stuk voor stuk bestuderen en wat demo’s posten. Leuk om hier in een verloren uurtje (whoehaha) eens over te bomen?

  3. Pingback: Dessign Patterns « Nathan

  4. what is we want add a method to DeluxeProgram class which is common only for this (DeluxeProgram ) class, so then how do we interact with that.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>