大话设计模式之策略模式(Strategy Pattern)

转载地址为:

http://www.cnblogs.com/chengxingliang/archive/2011/09/26/2185509.html


四个角色:抽象策略类(Strategy)、具体策略类(ConcreteStrategy)、场景角色(Context)、客户端(Client) 

        抽象策略类(Strategy):接口提供动作让场景角色Context调用各种具体策略类的算法。

        具体策略类(ConcreteStrategy):实现各种不同的策略算法

        场景角色(Context):使用Strategy的引用实例配置场景,并且提供一个接口获取结果。

        客户端(Client) :将具体策略类代入场景角色以计算出结果

 实现思路:多个具体策略类多种方式达到目的,Context场景角色中去让客户端选择具体策略类使用。这样在客户端即可非常方便的实现多种策略得到结果。

 类图:

应用场景:某销售部门,其内部员工可以8折购买货物,大客户7.5折,小客户9折购买。

分析:根据不同的客户,选择不同的计算方法,计算出打折之后的价格。

        下面我们在控制台程序去演示一下如何使用Strategy Pattern:

        一、 抽象策略类(Strategy)

    //策略类
abstract class PriceStrategy
{
abstract public double GetPrice(double price);
}

        二、具体策略类(ConcreteStrategy)

    //具体策略(员工价格策略)
class StaffPriceStrategy : PriceStrategy
{
public override double GetPrice(double price)
{
return price * 0.8;
}
}
//具体策略(大客户价格策略)
class BigCustomerPriceStrategy : PriceStrategy
{
public override double GetPrice(double price)
{
return price * 0.75;
}
}
//具体策略(小客户价格策略)
class SmallCustomerPriceStrategy : PriceStrategy
{
public override double GetPrice(double price)
{
return price * 0.9;
}
}
//具体策略(原价策略)
class OrigPriceStrategy : PriceStrategy
{
public override double GetPrice(double price)
{
return price;
}
}

        三、场景角色(Context)

    class CalculationContext
{
PriceStrategy priceStrategy;
public void SetStrategy(PriceStrategy priceStrg)
{
priceStrategy = priceStrg;
}
public double GetTotalPrice(double price)
{
return priceStrategy.GetPrice(price);
}
}

        四、客户端(Client) 

   class Program
{
static void Main(string[] args)
{
//未打折需付款1000元
double totalPrice = 1000.0;

CalculationContext calculate = new CalculationContext();
//计算出员工打折价
calculate.SetStrategy(new StaffPriceStrategy());
double staffPrice= calculate.GetTotalPrice(totalPrice);

//计算出大客户打折价
calculate.SetStrategy(new BigCustomerPriceStrategy());
double bigCustomerPrice = calculate.GetTotalPrice(totalPrice);

//计算出小客户打折价
calculate.SetStrategy(new SmallCustomerPriceStrategy());
double smallCustomerPrice = calculate.GetTotalPrice(totalPrice);

//计算出原价
            calculate.SetStrategy(new OrigPriceStrategy());
double origPrice = calculate.GetTotalPrice(totalPrice);

Console.WriteLine(string.Format("员工打折价{0}元,大客户打折价{1}元,小客户打折价{2}元,原价{3}元",
staffPrice, bigCustomerPrice, smallCustomerPrice, origPrice));
Console.ReadLine();
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值