`
chenying998179
  • 浏览: 25687 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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.

分享到:
评论

相关推荐

    Design Pattern Examples in C#.zip

    本压缩包“Design Pattern Examples in C#.zip”包含了多种设计模式的实例,旨在帮助开发者更好地理解和运用这些模式。 1. **单例模式** (Singleton): 这个模式确保一个类只有一个实例,并提供全局访问点。在C#中,...

    Design Pattern In c#

    《Design Pattern In C#》是一本深入探讨设计模式的书籍,专为使用C#编程语言的开发者准备。设计模式是软件工程中经过实践验证的、解决常见问题的有效方法,是经验丰富的开发者的智慧结晶。这本书以英文撰写,以其...

    strategy-pattern-in-unity

    在"learn-strategy-pattern-in-unity-in-less-than-15-minutes-master"这个项目中,我们可能会看到以下关键组件: 1. **策略接口(Strategy Interface)**:定义了所有策略类必须实现的方法,例如`MoveStrategy`,...

    Design Pattern in C#

    3. 行为型模式:包括策略模式(Strategy)、模板方法模式(Template Method)、观察者模式(Observer)、命令模式(Command)、责任链模式(Chain of Responsibility)、迭代器模式(Iterator)、访问者模式...

    策略模式 Strategy Pattern

    ### 策略模式 Strategy Pattern #### 概述 策略模式是一种行为设计模式,它使得算法可以在运行时被更改。这种模式允许一个类的行为或其算法在运行时根据需要进行改变,通过这种方式,我们可以轻松地扩展不同的算法...

    DoFactory Design Pattern Framework 3.5 C#

    总的来说,DoFactory Design Pattern Framework 3.5 C#是C#开发者学习和应用设计模式的强大工具,它将设计模式的理论知识与实际开发紧密结合,有助于提升开发者的专业技能和软件设计能力。无论是初学者还是经验丰富...

    The Factory Pattern(工厂模式)ppt

    工厂模式是一种常用的设计模式,它的主要目的是为了封装对象的创建过程,从而使得代码更加灵活,易于维护和扩展。在Head First设计模式中,工厂模式被用来解决对象创建时的“变化”问题,尤其是在需要根据条件动态...

    设计模式之策略模式(Strategy Pattern)

    在策略模式中,有三个主要角色:策略接口(Strategy Interface)、具体策略类(Concrete Strategy Classes)和上下文(Context)。策略接口定义了所有支持的算法的公共接口,这样上下文就可以通过这个接口来调用这些...

    The_Strategy_Book

    the strategy book.epub, 2nd edition by steve fortune,pfizer

    C#设计模式-吕震宇

    设计模式(22)-Strategy Pattern 设计模式(21)-Template Method Pattern 设计模式(20)-Visitor Pattern 设计模式(19)-Observer Pattern 设计模式(18)-Command Pattern 设计模式(17)-Chain of ...

    Design Patterns in C# A Hands-on Guide with Real-World Examples的例子源码

    15. 组合模式(Strategy Pattern):定义了一系列算法,并将每个算法封装起来,使它们可以互相替换,让算法的变化独立于使用算法的客户。 以上每个设计模式都包含了C#的源代码实现,读者可以通过阅读和实践这些代码...

    C# Design Pattern (C#设计模式PDF+源代码)

    如观察者模式(Observer)让多个对象可以订阅一个主题并接收通知,职责链模式(Chain of Responsibility)允许请求沿着处理者链传递,直到找到合适的处理者,而策略模式(Strategy)使算法可以在运行时选择和切换。...

    Design Patterns in C#

    - **策略模式**(Strategy Pattern) - **命令模式**(Command Pattern) - **迭代器模式**(Iterator Pattern) - **观察者模式**(Observer Pattern) - **中介者模式**(Mediator Pattern) - **备忘录模式...

    C#策略模式(Strategy Pattern)实例教程

    策略模式(Strategy Pattern)是一种行为设计模式,它使你能在运行时改变对象的行为。在C#中,策略模式常用于处理具有多种实现方式的情况,使得代码更加灵活,易于扩展。下面将详细讲解策略模式的概念、用途以及如何...

    设计模式之策略模式(Strategy Pattern)

    策略模式的主要组成部分包括上下文(Context)、策略接口(Strategy Interface)和具体策略类(Concrete Strategy Classes)。上下文维护一个对策略对象的引用,并使用这个引用来调用策略对象的算法。策略接口定义了...

    C# 7 and .NET Core Cookbook

    We start by running you through new features in C# 7, such as tuples, pattern matching, and so on, giving you hands-on experience with them. Moving forward, you will work with generics and the OOP ...

    Torque Control Strategy of an IPMSM Considering the Flux Variation of the

    Abstract—The variation of the remanence of the Permanent Magnet (PM), according to operating temperature and manufacturing tolerance, especially in the magnetization of the magnet, results in ...

    Programming.in.the.Large.with.Design.Patterns

    Each pattern is introduced with a non-technical example or story that illustrates the pattern concept. The details are described with Java code examples and UML diagrams. Each pattern description ...

Global site tag (gtag.js) - Google Analytics