一句话概述
策略模式作为一种软件设计模式,指对象有某个行为,但是在不同的场景中,该行为有不同的实现算法。比如每个人都要“交个人所得税”,但是“在美国交个人所得税”和“在中国交个人所得税”就有不同的算税方法。
实现一个中国和美国的个人税计算器
不用策略模式实现
public class TaxCalculator {
public static final int USA = 1000;
public static final int CHN = 1001;
// ......正常应该有一大堆计算公式,这里简单模拟
public double calculate(int country, int salary) {
double tax = 0;
if (country == USA) {
if (salary < 10000) {
tax = salary * 0.1;
} else if (salary >= 10000 && salary <= 20000) {
tax = salary * 0.2;
}
}
if (country == CHN) {
if (salary < 5000) {
tax = salary * 0.05;
} else if (salary >= 5000 && salary <= 10000) {
tax = salary * 0.1;
}
}
return tax;
}
}
用策略模式实现
1.定义策略接口:
public interface BaseTaxCalculateStrategy {
double calculate(int salary);
}
2.实现策略(这里用中国和美国举例,如果需要可以方便添加其他国家的实现)
public class USATaxCalculateStrategy implements BaseTaxCalculateStrategy {
@Override
public double calculate(int salary) {
double tax = 0;
if (salary < 10000) {
tax = salary * 0.1;
} else if (salary >= 10000 && salary <= 20000) {
tax = salary * 0.2;
}
return tax;
}
}
public class CHNTaxCalculateStrategy implements BaseTaxCalculateStrategy {
@Override
public double calculate(int salary) {
double tax = 0;
if (salary < 5000) {
tax = salary * 0.05;
} else if (salary >= 5000 && salary <= 10000) {
tax = salary * 0.1;
}
return tax;
}
}
3.开始应用
public class TaxCalculatorByStrategy implements BaseTaxCalculateStrategy{
private BaseTaxCalculateStrategy mStrategy;
@Override
public double calculate(int salary) {
return mStrategy.calculate(salary);
}
public void setStrategy(BaseTaxCalculateStrategy strategy){
mStrategy=strategy;
}
}
策略模式比较简单,以上就足够了。
网友评论