策略模式的使用:
一个计算税率的例子:
package chapter2; /** * 计算方法的接口 */ public interface CalculatorStrategy { public double calclate(double salary,double bonus); }
package chapter2; public class SimpleCalculatorStrategy implements CalculatorStrategy { private final static double SAQLARY_RATE=0.1; private final static double BONUS_RATE=0.15; @Override public double calclate(double salary, double bonus) { return salary*SAQLARY_RATE+bonus*BONUS_RATE; } }
package chapter2; /* 策略模式 */ public class TaxCalaculator { private final double salary; private final double bonus; //注入策略,使用了那种计算方案 private CalculatorStrategy CalculatorStrategy; public TaxCalaculator(double salary,double bonus){ this.salary=salary; this.bonus=bonus; } public double getSalary() { return salary; } public double getBonus() { return bonus; } /** * 子类重写 * @return */ protected double calcTax() { return CalculatorStrategy.calclate(salary,bonus); } public double calcuate() { return this.calcTax(); } public void setCalculatorStrategy(CalculatorStrategy calculatorStrategy) { CalculatorStrategy = calculatorStrategy; } }
调用:
package chapter2; public class Bank3 { public static void main(String[] args) { /** * 计算要交多少钱的税, 使用了策略模式 */ /* TaxCalaculator tor = new TaxCalaculator(1000d, 2000d){ @Override protected double calcTax() { return getBonus()*0.15+getSalary()*0.1; } }; double tax = tor.calcuate(); System.out.println(tax);*/ TaxCalaculator tor = new TaxCalaculator(1000d, 2000d); SimpleCalculatorStrategy scs = new SimpleCalculatorStrategy(); tor.setCalculatorStrategy(scs); System.out.println(tor.calcuate()); } }