Translate

Wednesday, September 18, 2013

strategy pattern c# example

What are we trying to solve?
Suppose you have an application where a customer gets a free car wash with every servicing. The kind of car wash he gets is based on how often he comes to the business. First time customers get a bronze wash and regular customers get a silver wash. Maybe in future we might even add a gold wash for extra loyal customers. The aim here is that the CarService class should not have to do switch statements. The reason for that is if we add a switch statement, such as this
switch (carwash)
            {
                case "bronze":
                    Console.WriteLine("bronze wash");
                    break;
                case "silver":
                    Console.WriteLine("silver wash");
                    break;
            }


everytime you add a new type of car wash, you violate the open close principle.

How to solve this?
Have the service class accept an implementation of an interface that perfoms the necessary action, into its constructor. This will be passed into the constructor at runtime.

Strategy Pattern is used when you want to switch algorithm at runtime. In the example below its the method Wash( ). In a real world example, obviously the algorithm would be a lot more complex than a simple Console.WriteLine( ).

The C# Code


using System;

namespace StrategyPattern
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var newCustomerService = new CarService(new BronzeWash()) {CustomerName = "Bob"};
            var regularCustomerService = new CarService(new SilverWash()) {CustomerName = "Ted"};

            newCustomerService.PerformMaintenance();
            regularCustomerService.PerformMaintenance();
        }
    }

    public class CarService
    {
        private readonly ICarwash _carwash;

        public CarService(ICarwash carwash)
        {
            _carwash = carwash;
        }

        public string CustomerName { get; set; }


        public void PerformMaintenance()
        {
            Console.WriteLine("*******************************");
            Console.WriteLine("Servicing {0}", CustomerName);
            Console.WriteLine("Oil Change");
            Console.WriteLine("Tire Pressure check");
            _carwash.Wash();
            Console.WriteLine("*******************************");
        }
    }

    public interface ICarwash
    {
        void Wash();
    }

    public class BronzeWash : ICarwash
    {
        public void Wash()
        {
            Console.WriteLine("Bronze wash");
        }
    }

    public class SilverWash : ICarwash
    {
        public void Wash()
        {
            Console.WriteLine("Silver wash");
        }
    }
}


Output:

1 comment:

  1. Hi Vivek, This is one of the best examples for Strategy Pattern. Short and crisp. Thanks!

    ReplyDelete

Comments will appear once they have been approved by the moderator