首页 > 其他 > 详细

设计模式-策略模式

时间:2020-04-29 21:15:10      阅读:55      评论:0      收藏:0      [点我收藏+]

定义:

策略模式定义了一系列的算法,并将每一个算法封装起来,使它们可以互相替换

个人理解:

类似委托的作用,将算法通过客户端传入,起到订制的作用

 

客户端:

IActive active = new HighActive();
decimal payPrice = new ActiveExecutor().Execute(active);

 

策略执行类:

    public class ActiveExecutor
    {
        public decimal Execute(IActive active)
        {
            decimal orderPrice = 200M;
            return active.Rule(orderPrice);
        }
    }

 

策略类:

    public interface IActive
    {
        //int DiscountType { get; }
        decimal Rule(decimal orderPrice);
    }
    public class LowActive : IActive
    {
        public decimal Rule(decimal orderPrice)
        {
            if (orderPrice < 100M)
            {
                return orderPrice - 1M;
            }
            else
            {
                return orderPrice - 5M;
            }
        }
    }
    public class MiddleActive : IActive
    {
        public decimal Rule(decimal orderPrice)
        {
            if (orderPrice < 100M)
            {
                return orderPrice - 10M;
            }
            else
            {
                return orderPrice - 20M;
            }
        }
    }
    public class HighActive : IActive
    {
        public decimal Rule(decimal orderPrice)
        {
            if (orderPrice < 100M)
            {
                return orderPrice - 20M;
            }
            else
            {
                return orderPrice - 50M;
            }
        }
    }

 

设计模式-策略模式

原文:https://www.cnblogs.com/fanfan-90/p/12804367.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!