日期:2014-05-18  浏览次数:20713 次

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 :