浅析.net策略模式
2014-12-18来源:易贤网

对于策略模式的理解:当一个业务有多种需求时候,在某个时候需要使用不同的方式来计算结果。这时候不同的方式可以理解为不同的策略来解决同样的问题。 例如:商场收银系统计算价格,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());

名单

更多信息请查看IT技术专栏

2026公务员·事业单位培训课程试听报名

  • 报班类型
  • 姓名
  • 手机号
  • 验证码
推荐信息