策略模式有两个主要角色,一个是主类,一个是策略类,通过主类的构造函数将策略类注入到主类,从而实现调用不同的策略。
典型的例子就是收银策略,正常收费,八折、五折,满200减50等等。
示例代码
package designMode.strategy;
public class CashContext {
private CashSuper cashSuper;
public CashContext(CashSuper cashSuper) {
this.cashSuper = cashSuper;
}
public double getResult(double money){
return cashSuper.acceptCash(money);
}
}
package designMode.strategy;
public abstract class CashSuper {
public abstract double acceptCash(double money);
}
package designMode.strategy;
public class CashNormal extends CashSuper {
@Override
public double acceptCash(double money) {
return money;
}
}
package designMode.strategy;
public class CashRebate extends CashSuper {
private double moneyRebate = 0.8;
public CashRebate(double moneyRebate) {
this.moneyRebate = moneyRebate;
}
@Override
public double acceptCash(double money) {
return money*moneyRebate;
}
}
package designMode.strategy;
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;
}
}
package designMode.strategy;
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
CashContext cashContext = null;
Scanner scanner = new Scanner(System.in);
System.out.println("请输入打折方式(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 += "打八折";
break;
default:
System.out.println("请输入1/2/3");
break;
}
double totalPrices = 0;
System.out.print("请输入单价:");
double price = scanner.nextDouble();
System.out.println("请输入数量:");
double num = scanner.nextDouble();
totalPrices = cashContext.getResult(price * num);
System.out.println("单价:" + price + ",数量:" + num + ",类型:" + type + ",合计:" + totalPrices);
scanner.close();
}
}