网站首页  汉语字词  英语词汇  考试资料  写作素材  旧版资料

请输入您要查询的考试资料:

 

标题 浅析.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());
    名单
随便看

 

在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。

 

Copyright © 2002-2024 cuapp.net All Rights Reserved
更新时间:2025/5/18 11:04:29