策略模式

来源:互联网 发布:pptv网络电视官方下载 编辑:程序博客网 时间:2024/06/06 09:58

一、理解

     在大话设计模式中,策略模式的定义如下:策略模式(Strategy)定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。

     策略模式是根据商场收银系统的需要而产生的,针对商场收银系统,刚开始使用了简单工厂模式来解决该问题,但是,针对该问题,简单工厂知识解决对象的创建问题,但在实际情况中,商场是经常性地更改相关打折额度和返利额度,这样导致在每次维护或者扩展收费方式都要改动这个工厂,如此情况,简单工厂模式不再是针对商场收银系统最好的解决办法,由此产生了策略模式。

     策略模式方便了这些算法之间的相互替换。

二、UML示例图

                           

三、优缺点

1、优点:

      减少了各种算法类与使用算法类之间的耦合;

      策略模式中的Strategy类层次为Context定义了一系列的可供重用的算法或行为;

      简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试;

      将判断不同的算法类型放到了客户端中,这样可以消除了条件语句;

2、缺点:

      但是在基本的策略模式中,选择所用具体实现的职责由客户端对象承担了,并转给策略模式的CashContext独享,这样对客户端带来了选择判断的压力,从而产生了策略模式与简单工厂模式的结合,将选择判断的问题转交给了CashContex,减轻了客户端对象的压力。

     策略模式与简单工厂模式结合以后还是有一些缺陷:CashContext中用到了swich语句,如果需要增加一种算法,则必须要修改CashContext中的swich代码。

四、策略模式实际代码

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 策略模式{    class Program    {        static void Main(string[] args)        {            Context context;            context = new Context(new ConcreteStrategyA());            context.ContextInterface();            context = new Context(new ConcreteStrategyB());            context.ContextInterface();            context = new Context(new ConcreteStrategyC());            context.ContextInterface();            Console.Read();        }    }            //抽象算法类    abstract class Strategy    {        //算法方法        public abstract void AlgorithmInterface();    }    //具体算法A    class ConcreteStrategyA : Strategy    {        //算法A实现方法        public override void AlgorithmInterface()        {            Console.WriteLine("算法A实现");        }    }    //具体算法B    class ConcreteStrategyB : Strategy    {        //算法B实现方法        public override void AlgorithmInterface()        {            Console.WriteLine("算法B实现");        }    }        //具体算法C    class ConcreteStrategyC : Strategy    {        public override void AlgorithmInterface()        {            Console.WriteLine("算法C实现");        }    }        //上下文    class Context    {        Strategy strategy;        public Context(Strategy strategy)        {            this.strategy = strategy;        }        //上下文接口        public void ContextInterface()        {            strategy.AlgorithmInterface();        }    }}



1 0
原创粉丝点击