模式定义
策略模式定义了一系列算法,并将每一个算法封装起来,而且是他们之间可以相互切换。
不同理财工具理财率不一样,一般写法
public class FinaceManager {
public enum Finace{
ZHI_FU_BAO,PEAKMAIN
}
private float zhifubaoFinace(int month,int money){
if (month == 3) {
return money + money * 0.047f / 12 * month;
}
if (month == 6) {
return money + money * 0.05f / 12 * month;
}
if (month == 12) {
return money + money * 0.06f / 12 * month;
}
throw new IllegalArgumentException("月份不对");
}
private float peakmainFinance(int month, int money) {
if (month == 3) {
return money + money * 0.09f / 12 * month;
}
if (month == 6) {
return money + money * 0.112f / 12 * month;
}
if (month == 12) {
return money + money * 0.12f / 12 * month;
}
throw new IllegalArgumentException("月份不对");
}
/**
* 获取计算的金额
*/
public float finance(int month,int money,Finace finace){
switch (finace){
case ZHI_FU_BAO:
return zhifubaoFinace(month,money);
case PEAKMAIN:
return peakmainFinance(month,money);
default:
return 0;
}
}
}
测试
public class Client {
public static void main(String[] args) {
FinaceManager finaceManager=new FinaceManager();
float money = finaceManager.finance(3, 9000, FinaceManager.Finace.ZHI_FU_BAO);
System.out.println(money);
}
}
策略模式写
IFinaceManager
public interface IFinaceManager {
float finace(int month,int money);
}
ZhifubaoFinace
public class ZhifubaoFinace implements IFinaceManager {
@Override
public float finace(int month, int money) {
if (month == 3) {
return money + money * 0.047f / 12 * month;
}
if (month == 6) {
return money + money * 0.05f / 12 * month;
}
if (month == 12) {
return money + money * 0.06f / 12 * month;
}
throw new IllegalArgumentException("月份不对");
}
}
peakmainFinance
public class peakmainFinance implements IFinaceManager {
@Override
public float finace(int month, int money) {
if (month == 3) {
return money + money * 0.09f / 12 * month;
}
if (month == 6) {
return money + money * 0.112f / 12 * month;
}
if (month == 12) {
return money + money * 0.12f / 12 * month;
}
throw new IllegalArgumentException("月份不对");
}
}
FinaceContext这个类是多余的,实际开发过程中可以不要
public class FinaceContext {
private IFinaceManager mFinace;
public FinaceContext(IFinaceManager finaceManager) {
this.mFinace = finaceManager;
}
public float finace(int month, int money) {
return mFinace.finace(month, money);
}
}
测试
public class Client {
public static void main(String[] args) {
IFinaceManager finaceManager=new peakmainFinance();
FinaceContext context=new FinaceContext(finaceManager);
float money = context.finace(3, 9000);
//float money = finaceManager.finace(3, 9000);
System.out.println(money);
}
}