zoukankan      html  css  js  c++  java
  • 一日一技:策略模式(附demo)

    概念

    在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

    在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

    策略其实就是做一件事情有很多很多的方法,比如说一个商场要搞促销,促销的方式有可能有很多:打折啊,满100返50啊、积分等等之类的。这种不同的促销方式在我们系统中表示就是一个一个的策略。

    实现方式

    1、定义策略接口

       public interface IPromotion
        {
            /// <summary>
            /// 根据原价和策略计算新价格
            /// </summary>
            /// <param name="originPrice">原价</param>
            /// <returns></returns>
            double GetPrice(double originPrice);
        }

    2、实现不同的接口1、2

     public class Discount : IPromotion
        {
            public double GetPrice(double originPrice)
            {
                Console.WriteLine("打八折:");
                return originPrice * 0.8;
            }
        }
    
        public class MoneyBack : IPromotion
        {
            public double GetPrice(double originPrice)
            {
                Console.WriteLine("满100返50");
                return originPrice - (int)originPrice / 100 * 50;
            }
        }

    3、定义策略工厂

    public class PromotionContext
        {
            private IPromotion p = null;
    
            public PromotionContext(IPromotion p)
            {
                this.p = p;
            }
    
            public double GetPrice(double originPrice)
            {
                // 默认策略
                if (this.p == null)
                {
                    this.p = new Discount();
                }
                return this.p.GetPrice(originPrice);
            }
    
            /// <summary>
            /// 更改策略的方法
            /// </summary>
            /// <param name="p"></param>
            public void ChangePromotion(IPromotion p)
            {
                this.p = p;
            }
        }

    4、测试策略,切换不同的实现方式

     public IActionResult Index()
            {
                // 默认策略:打八折的策略
                PromotionContext pc = new PromotionContext(null);
                Console.WriteLine(pc.GetPrice(200));
    
                // 更改策略:满100返50的策略
                pc.ChangePromotion(new MoneyBack());
                Console.WriteLine(pc.GetPrice(155.9));
    
                return View();
            }

    结果如下

    开源地址

    https://gitee.com/conanOpenSource_admin/Example/tree/master/%E7%AD%96%E7%95%A5

  • 相关阅读:
    微信小程序地图组件中的include-points怎样缩放视野并将所有坐标点在规定的视野内展示?
    两种常见的mysql集群架构
    layui+oss阿里云附件上传回调报错问题
    redis hash过期时间
    Static和Extern关键字理解
    代理模式
    中介者模式
    访问者模式
    模板方法模式
    迭代器模式
  • 原文地址:https://www.cnblogs.com/lyl6796910/p/14509534.html
Copyright © 2011-2022 走看看