策略模式:它定義了算法家族,分別封裝起來,讓他們之間能夠互相替換,此模式讓算法的變化不會影響使用算法的用戶。算法
針對商城收銀模式,打折,返現促銷等的例子:ide
打折仍是促銷其實都是一些算法,能夠用工廠模式來生成算法對象,但算法自己只是一種策略,重要的是這些算法隨時均可能替換的,而封裝變化點是咱們面向對象的一種重要的思惟方式,首先來看下策略模式的結構圖和基本代碼:this
1)結構圖spa
2)代碼3d
strategy類,定義全部支持的方法的公共接口code
public abstract class Strategy { //算法公告接口 public abstract void AlgorithmInterface(); }
ConcreteStrategy,封裝了具體的方法或行爲,繼承strategy對象
public class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法A的實現"); } } public class ConcreteStrategyB :Strategy { public override void AlgorithmInterface() { Console.WriteLine("算法B的實現"); } }
Context,用一個ConcreteStrategy來配置,維護一個對Strategy對象的引用blog
public class Context { private Strategy strategy; public Context(Strategy strategy) { this.strategy = strategy; } //上下文接口 public void ContextInterface() { strategy.AlgorithmInterface(); } }
客戶端代碼:繼承
static void Main(string[] args) { Context context; context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context=new Context(new ConcreteStrategyB()); context.ContextInterface(); Console.ReadLine(); }
用策略模式來實現商場收費:接口
定義公共接口和各類收費策略
//定義公共收費接口類 public abstract class CashSuper { //公共的收費接口 public abstract double acceptCash(double money); } //定義各類收費策略 public class CashNomal:CashSuper { public override double acceptCash(double money) { return money; } } public class CashRebate:CashSuper { private double rebate = 1; public CashRebate(string rebate) { this.rebate = Convert.ToDouble(rebate); } public override double acceptCash(double money) { return money * this.rebate; } } public class CashReturn:CashSuper { public double condition = 0.0d; public double returnMoney = 0.0d; public CashReturn(string condition, string returnMoney) { this.returnMoney = Double.Parse(returnMoney); this.condition = Double.Parse(condition); } public override double acceptCash(double money) { double result = money; if(money >= condition) { result = money - Math.Floor(result/condition)*returnMoney; } return result; } }
定義Context:
public class CashContext { private CashSuper cashsuper; public CashContext(CashSuper cs) { cashsuper = cs; } public double GetResult(double money) { return cashsuper.acceptCash(money); } }
客戶段代碼:
static void Main(string[] args) { double totle = 500.0d; double result = 0.0d; CashContext context; context = new CashContext(new CashNomal()); result = context.GetResult(totle); Console.WriteLine(result); context = new CashContext(new CashRebate("0.3")); result = context.GetResult(totle); Console.WriteLine(result); context =new CashContext(new CashReturn("300","50")); result = context.GetResult(totle); Console.WriteLine(result); Console.ReadLine(); }