Q:策略模式的特点
A:
- 具体算法从具体的业务方法中独立出来
- 策略模式是同行为的不同实现
Q:什么时候使用策略模式
A:多个if-else使用策略模式
收费对象类
java
public class CashContext {
private CashStrategy cashStrategy;
public double getMoney(double money) {
return cashStrategy.acceptCash(money);
}
}
收费策略接口
java
public interface CashStrategy { double acceptCash(double money); }
正常收费类
java
public class NormalCash implements CashStrategy {
@Override
public double acceptCash(double money) {
return money;
}
}
打折收费类
java
public class RebateCash implements CashStrategy {
private double discounts = 10;
@Override
public double acceptCash(double money) {
return money * discounts / 10;
}
}
返利收费类
java
public class ReturnCash implements CashStrategy {
private double condition = 0;
private double rebate = 0;
@Override
public double acceptCash(double money) {
if (money >= condition) {
money -= Math.floor(money / condition) * rebate;
}
return money;
}
}
演示类
java
public class Demo {
public static void main(String[] args) {
String discounts = "满300减100";
CashContext cc = new CashContext();
switch (discounts) {
case "正常收费":
cc.setCashStrategy(new NormalCash());
break;
case "打9折":
cc.setCashStrategy(new RebateCash(9));
break;
case "满300减100":
cc.setCashStrategy(new ReturnCash(300, 100));
break;
}
double price = 400;
double money = cc.getMoney(price);
System.out.println("优惠后的费用为:" + money);
}
}