策略模式定义:
策略模式定义了一系列的算法,并将每一个算法封装起来,而且使它们还可以相互替换,策略模式让算法独立于使用它的客户而独立变化。
The Strategy Pattern defines a family of algorithms,encapsulates each one,and makes them interchangeable. Strategy lets the algorithm vary independently from clients that use it.
策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同额方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。
策略模式UML类图:
角色分析:
namespace DesignPattern.策略模式 { //现金收费抽象类 abstract class CashSuper { /* * 现金收取超类的抽象方法,收取现金,参数为原价,返回为当前价 */ public abstract double AcceptCash(double cash); } }具体策略类
namespace DesignPattern.策略模式 { //正常收费子类 class CashNormal : CashSuper { public override double AcceptCash(double cash) { return cash; } } //打折收费子类 class CashRebate : CashSuper { private double moneyRebate = 1; /* * 打折收费,初始化时,必须要输入折扣费,如八折(0.8) */ public CashRebate(double moneyRebate) { this.moneyRebate = moneyRebate; } public override double AcceptCash(double cash) { return moneyRebate * cash; } } //返利收费子类 class CashReturn : CashSuper { private double moneyCondition = 0;//返利的条件 private double moneyReturn = 0;//返利的金额 public CashReturn(double moneyCondition, double moneyReturn) { this.moneyCondition = moneyCondition; this.moneyReturn = moneyReturn; } public override double AcceptCash(double cash) { double result = cash; if (cash > moneyCondition) { result = cash - Math.Floor(cash / moneyCondition) * moneyReturn; } return result; } } }应用场景类
namespace DesignPattern.策略模式 { class CashContext { private CashSuper cashContext; public CashContext(String type) { switch (type) { case "正常收费": cashContext = new CashNormal(); break; case "打8折": cashContext = new CashRebate(0.8); break; case "满300反100": cashContext = new CashReturn(300, 100); break; } } public double GetResult(double cash) { return cashContext.AcceptCash(cash); } } }测试类
namespace DesignPattern.策略模式 { class Strategy { public static void Main() { double cash = 330; double result = 0; CashContext context = null; context = new CashContext("打8折"); result = context.GetResult(cash); Console.WriteLine("打八折后的价格:{0}", result); context = new CashContext("满300反100"); result = context.GetResult(cash); Console.WriteLine("满300反100的价格:{0}", result); } } }