2019-04-17设计模式-策略模式
2019-04-17 本文已影响0人
猫KK
定义一些列算法,将它们封装起来并且使它们可以相互调用。主要用来解决多个if-else问题
来一个简单的例子:金融理财,每一个理财产品就相当于一个策略。计算每个产品的效益,按正常思路来:
//新建一个金融类
class Finance {
//计算效益
public float moneyRate(int month, int money, int type) {
//假定 type = 1 为其中的一个理财产品
if (type == 1) {
//分别计算使用不同月份的效益
if (month == 3) {
return (float) (money + month * money * 0.09 / 12);
}
if (month == 6) {
return (float) (money + month * money * 0.10 / 12);
}
if (month == 9) {
return (float) (money + month * money * 0.11 / 12);
}
throw new IllegalStateException("没有对应的期限");
}
//假定 type = 2 为另一个理财产品
if (type == 2) {
//分别计算使用不同月份的效益
if (month == 3) {
return (float) (money + month * money * 0.10 / 12);
}
if (month == 6) {
return (float) (money + month * money * 0.11 / 12);
}
if (month == 9) {
return (float) (money + month * money * 0.12 / 12);
}
throw new IllegalStateException("没有对应的期限");
}
throw new IllegalStateException("没有对应的产品");
}
}
使用方法如下
public class FinanceClient {
public static void main(String[] args) {
Finance finance = new Finance();
float money = finance.moneyRate(3, 10000, 1);
System.out.println("------->" + money);
}
}
上面的写法,假如不在需要拓展,看起来还行,当假如增加一种 type = 3 的产品,就需要在Finance类中增加一个if条件语句。如果产品越来越多,if语句就会越来越多,Finance会显得特别的臃肿,下面使用策略模式来改写
public interface IFinance {
float moneyRate(int month, int money);
}
抽象出一个计算的接口,让子类去实现自己对应的计算方法,即对应的策略
//type1 产品的策略方法实现
public class Type1 implements IFinance {
@Override
public float moneyRate(int month, int money) {
if (month == 3) {
return (float) (money + month * money * 0.10 / 12);
}
if (month == 6) {
return (float) (money + month * money * 0.11 / 12);
}
if (month == 12) {
return (float) (money + month * money * 0.12 / 12);
}
throw new IllegalStateException("没有对应的期限");
}
}
一般来说,还需要一个类似Context的类,用来管理
public class Context {
private IFinance finance;
public Context(IFinance finance) {
this.finance = finance;
}
public float moneyRate(int month, int money) {
return finance.moneyRate(month, money);
}
}
最后使用
public class FinanceClient {
public static void main(String[] args) {
Context context = new Context(new Type1());
float money = context.moneyRate(3, 10000);
System.out.println("---->" + money);
}
}
完