UML类图:

算法父类:
package com.jthao.design.des.strategy;
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
算法类A:
package com.jthao.design.des.strategy;
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
System.out.println("算法A");
return money;
}
}
算法类B:
package com.jthao.design.des.strategy;
public class CashRebate extends CashSuper {
private double moneyRebate = 1d;
public CashRebate(String moneyRebate) {
this.moneyRebate = Double.parseDouble(moneyRebate);
}
@Override
public double acceptCash(double money) {
System.out.println("算法B");
return money * moneyRebate;
}
}
Context上下文:
package com.jthao.design.des.strategy;
public class CashContext {
CashSuper cs;
public CashContext(String type) {
switch (type) {
case "正常收费":
CashNormal cs0 = new CashNormal();
cs = cs0;
break;
case "打8折":
CashRebate cs2 = new CashRebate("0.8");
cs = cs2;
break;
}
}
public double getResult(double money) {
return cs.acceptCash(money);
}
}
测试类:
package com.jthao.design.des.strategy;
public class StrategyTest {
public static void main(String[] args) {
CashContext cashContext = new CashContext("打8折");
System.out.println(cashContext.getResult(100));
}
}