如何理解.net策略模式

本篇内容主要讲解“如何理解.net策略模式”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何理解.net策略模式”吧!

对于策略模式的理解:当一个业务有多种需求时候,在某个时候需要使用不同的方式来计算结果。这时候不同的方式可以理解为不同的策略来解决同样的问题。 例如:商场收银系统计算价格,1:正常计算 2:商品打折计算,3:满300减100等方式。就可以按三种策略来处理需求。

简单的说:策略模式就是用来封装算法的,但在实践中,我们发现可以用他来封装几乎任何类型的规则,只要在分析过程中听到需要在不同的时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。

复制代码 代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DesignModel
{
    /// <summary>
    /// 策略模式
    /// </summary>
    public class TacticsModel
    {
        public string type { get; set; }
        public virtual string GetResult()
        {
            return "";
        }
    }
    public class Normal:TacticsModel
    {
        public override string GetResult()
        {
            return "正常计算价格";
        }
    }
    public class Discount : TacticsModel
    {
        public override string GetResult()
        {
            return "按打折计算价格";
        }
    }
    public class Preferential : TacticsModel
    {
        public override string GetResult()
        {
            return "满300减100活动";
        }
    }
    public class CashContext
    {
        TacticsModel tm = null;
        public CashContext(string type)
        {
            switch (type)
            {
                case "1":
                    tm = new Normal();
                    break;
                case "2":
                    tm = new Discount();
                    break;
                case "3":
                    tm = new Preferential();
                    break;
                default:
                break;
             }
        }
        public string GetResult()
        {
            return tm.GetResult();
        }
    }
}

这种方式和简单工厂方式差不多,只是有稍微区别。 简单工厂模式需要暴漏给客户端两个类,策略模式和工厂模式的简单结合只暴漏了一个CashContext类

客户端调用代码:

复制代码 代码如下:

   Console.WriteLine("请计算类型1正常,2打折,3优惠:");
   string type = Console.ReadLine();
   CashContext cc = new CashContext(type);
   Console.WriteLine(cc.GetResult());

结果:

如何理解.net策略模式

如何理解.net策略模式

到此,相信大家对“如何理解.net策略模式”有了更深的了解,不妨来实际操作一番吧!这里是亿速云网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!