本文共 3368 字,大约阅读时间需要 11 分钟。
《大话设计模式》阅读笔记和总结。原书是C#编写的,本人用Java实现了一遍,包括每种设计模式的UML图实现和示例代码实现。
目录: Github地址:
定义:策略模式(Strategy)它定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
UML图:
代码实现:
Strategy类,定义所有支持的算法的公共接口
abstract class Strategy{ //算法方法 public abstract void AlgorithmInterface();}
ConcreteStrategy,封装了具体的算法或行为
class ConcreteStrategyA extends Strategy{ @Override public void AlgorithmInterface() { System.out.println("算法A实现"); }}class ConcreteStrategyB extends Strategy{ @Override public void AlgorithmInterface() { System.out.println("算法B实现"); }}class ConcreteStrategyC extends Strategy{ @Override public void AlgorithmInterface() { System.out.println("算法C实现"); }}
Context,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用
class Context{ Strategy strategy; public Context(Strategy strategy){ this.strategy = strategy; } // 上下文接口 public void ContextInterface(){ strategy.AlgorithmInterface(); }}
客户端代码
public class StrategyPattern { public static void main(String[] args){ Context context; context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new Context(new ConcreteStrategyB()); context.ContextInterface(); context = new Context(new ConcreteStrategyC()); context.ContextInterface(); }}
运行结果
算法A实现算法B实现算法C实现
例子:商场在卖衣服的时候有时候会采取促销手段,有的会原价出售,有的会打折,有的会满减。用程序模拟这个过程,计算最终的费用。
UML图:
代码:
现金收费抽象类
public abstract class CashSuper { /** * 现金收取超类方法,传入原价,返回当前价 */ public abstract double acceptCash(double money);}
正常收费子类
public class CashNormal extends CashSuper { @Override public double acceptCash(double money) { // 正常收费,返回原价 return money; }}
打折收费子类
public class CashRebate extends CashSuper { private double moneyRebate = 1; public CashRebate(double moneyRebate){ this.moneyRebate = moneyRebate; } @Override public double acceptCash(double money) { // 正常收费,返回原价 return money*moneyRebate; }}
满减收费子类
public class CashReturn extends CashSuper { private double moneyCondition = 0;// 满足的条件 private double moneyReturn = 0;//返利 public CashReturn(double moneyCondition,double moneyReturn){ this.moneyCondition = moneyCondition; this.moneyReturn = moneyReturn; } @Override public double acceptCash(double money) { double result = money; if (money>=moneyCondition){ result = money - Math.floor(money/moneyCondition)*moneyReturn; } return result; }}
CashContext类
public class CashContext { private CashSuper cs; public CashContext(CashSuper cs){ this.cs = cs; } public double GetResult(double money){ return cs.acceptCash(money); }}
客户端代码
public class Main { public static void main(String[] args){ String type = "满300减100"; CashContext cc = null; switch (type){ case "正常收费": cc = new CashContext(new CashNormal()); break; case "满300减100": cc = new CashContext(new CashReturn(300,100)); break; case "打8折": cc = new CashContext(new CashRebate(0.8)); break; } double resultPrice = cc.GetResult(520); System.out.println("最终的价格是:"+resultPrice); }}
运行结果
最终的价格是:420.0
转载地址:http://zgfzo.baihongyu.com/