策略模式:定义一系列的算法,把每一个算法封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。也称为政策模式(Policy)。
目的:为了让算法和对象独立出来,代替if判断方式
举例:商场商品促销方法
//声明一个CashSuper对象,通过构造方法,传入具体的收费策略,
//getResult()方法的功能为根据收费策略的不同获得计算结果。
public class CashContext {
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper) {
this.cashSuper = cashSuper;
}
public double getResult(double money) {
return cashSuper.acceptCash(money);
}
}
//策略类,为抽象类,抽象出收费的方法供子类实现。
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
//没有任何活动的情况,正常收费,返回原价。
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
//打折活动,根据折扣返回打折后的价格。
public class CashRebate extends CashSuper {
private double moneyRebate = 1; //折扣
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money * moneyRebate;
}
}
//返利活动,输入返利条件和返利值,比如满300返100
public class CashReturn extends CashSuper {
private double moneyConditation = 0.0; //返利条件
private double moneyReturn = 0.0d; //返利值
public CashReturn(double moneyConditation, double moneyReturn) {
this.moneyConditation = moneyConditation;
this.moneyReturn = moneyReturn;
}
@Override
public double acceptCash(double money) {
double result = money;
if (money >= moneyConditation) {
result = money - Math.floor(money / moneyConditation) * moneyReturn;
}
return result;
}
}
//客户端
public class Client {
public static void main(String[] args) {
CashContext cashContext = null;
Scanner scanner = new Scanner(System.in);
System.out.print("请输入打折方式(1/2/3):");
int in = scanner.nextInt();
String type = "";
switch (in) {
case 1:
cashContext = new CashContext(new CashNormal());
type += "正常收费";
break;
case 2:
cashContext = new CashContext(new CashReturn(300, 100));
type += "满300返100";
break;
case 3:
cashContext = new CashContext(new CashRebate(0.8));
type += "打8折";
break;
default:
System.out.println("请输入1/2/3");
break;
}
double totalPrices = 0;
System.out.print("请输入单价:");
double price = scanner.nextDouble();
System.out.print("请输入数量:");
double num = scanner.nextDouble();
totalPrices = cashContext.getResult(price * num);
System.out.println("单价:" + price + ",数量:" + num + ",类型:" + type + ",合计:" + totalPrices);
scanner.close();
}
}