大话设计模式之策略模式(strategy)
策略模式:它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化不会影响使用算法的用户。
针对商城收银模式,打折,返现促销等的例子:
打折还是促销其实都是一些算法,可以用工厂模式来生成算法对象,但算法本身只是一种策略,重要的是这些算法随时都可能替换的,而封装变化点是我们面向对象的一种重要的思维方式,首先来看下策略模式的结构图和基本代码:
1)结构图
2)代码
strategy类,定义所有支持的方法的公共接口
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对象的引用
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(); }