• 策略模式


    策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换。策略模式让算法独立于使用它的客户而独立变化。

    UML图如下:

    Strategy是一个抽象类,其中有一个抽象方法Algorithmlnterface(),继承Stratety抽象类的就是具体的算法类,而重写基类的AlgorithmInterface()方法,返回具体算法的返回值。例如:一个商场收银的举例《大话设计模式》

        public abstract class AlgrithmSuper
        {
            public abstract double AlgrithmResult(double money);
        }
    AlgrithmSuper
        /// <summary>
        /// 按折扣打折
        /// </summary>
        public class AlgrithmA:AlgrithmSuper
        {
            private double MoneyRebate = 1;
            
            public AlgrithmA(string moneyRebate)
            {
                this.MoneyRebate = double.Parse(moneyRebate);
            }
    
            public override double AlgrithmResult(double money)
            {
                return money * this.MoneyRebate;
            }
        }
    AlgrithmA
        /// <summary>
        /// 满300减100
        /// </summary>
        public class AlgrithmB:AlgrithmSuper
        {
            private double LimitMoney;
            private double PlusMoney;
            public AlgrithmB(double limitmoney,double pluemoney)
            {
                this.LimitMoney = limitmoney;
                this.PlusMoney = pluemoney;
            }
            public override double AlgrithmResult(double money)
            {
                return money > LimitMoney ? money - this.PlusMoney : money;
            }
        }
    AlgrithmB
        /// <summary>
        /// 原价
        /// </summary>
        public class AlgrithmC:AlgrithmSuper
        {
            public AlgrithmC()
            { }
            public override double AlgrithmResult(double money)
            {
                return money;
            }
        }
    AlgrithmC

      ==上述的AlgrithmSuper抽象类中有一个抽象方法就是用来计算并返回实际该收的钱,而继承它的三个类AlgrithmA、AlgrithmB、AlgrithmC就是三个算法分别实现了打折、满xx返xx、原价。

    由上述的类,我们现在可以这样调用:

    AlgrithmSuper algrithm=new AlgrithmA(0.80)
    double result= algrithm.AlgrithmResult(1000);

    而策略模式,则用一个策略上下文,维护一个对 策略(Strategy,AlgrithmSuper) 对象的引用,即:

       public  class StrategyContext
        {
           private AlgrithmSuper Algrithm = null;
    
           public StrategyContext(AlgrithmSuper algrithm)
           {
               this.Algrithm = algrithm;
           }
           public double GetResult(double money)
           {
               return Algrithm.AlgrithmResult(money);
           }
        }

    调用时:
      StrategyContext context=new StrategyContext(new AlgrithmA(0.80));
      context.GetResult(1000);

    至此,对于策略模式中通过基类抽象类对各个实际算法的封装,并通过一个策略上下文实现依赖注入。

  • 相关阅读:
    微信小程序,本地和真机测试都是好的,但体验版扫码显示空白页
    redis cluster 集群从节点无法读取值 (error) MOVED 原因和解决方案
    mysql笔记
    微信小程序对接通联支付
    解决win7凭据重启后消失的问题
    友链
    第三方登录--QQ登录--单体应用
    【笔记-错误】springCloud-alibaba-feign集成sentinel的启动报错
    【笔记】 springCloud--Alibaba--服务注册和服务发现
    【笔记】springCloud--Alibaba--nacos介绍----启动报错解决方案
  • 原文地址:https://www.cnblogs.com/wupeiqi/p/3349628.html
Copyright © 2020-2023  润新知