极速理解设计模式系列:8.策略模式(Strategy Pattern)

四个角色:抽象策略类(Strategy)、具体策略类(ConcreteStrategy)、场景角色(Context)、客户端(Client)
抽象策略类(Strategy):接口提供动作让场景角色Context调用各种具体策略类的算法。
具体策略类(ConcreteStrategy):实现各种不同的策略算法
场景角色(Context):使用Strategy的引用实例配置场景,并且提供一个接口获取结果。
客户端(Client) :将具体策略类代入场景角色以计算出结果
实现思路:多个具体策略类多种方式达到目的,Context场景角色中去让客户端选择具体策略类使用。这样在客户端即可非常方便的实现多种策略得到结果。
类图:
极速理解设计模式系列:8.策略模式(Strategy Pattern)
应用场景:某销售部门,其内部员工可以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(); } }

如需源码请点击 StrategyPattern.rar 下载。
Tags: 

延伸阅读

最新评论

发表评论