策略模式结构
策略A:直接打九折
策略B:满200之后全部打八五折
策略C:满200之后的价格打七折处理
结构
定义异常
考虑到输入金额会出错,自定义一个异常
public class AmountOutOfArangeException extends Exception{
public AmountOutOfArangeException(String message){
super(message);
}
}
定义一个折扣接口
public interface Discount {
void discount(double amount) throws AmountOutOfArangeException;
}
定义折扣策略
- 折扣A
public class DiscountA implements Discount{
@Override
public void discount(double amount) throws AmountOutOfArangeException{
if(amount<=0)
throw new AmountOutOfArangeException("至少买点吧");
else{
double money;
money = amount*0.9;
System.out.println("使用A策略实际花费"+money+"元");
}
}
}
- 折扣B
public class DiscountB implements Discount{
@Override
public void discount(double amount) throws AmountOutOfArangeException{
if(amount<=0){
throw new AmountOutOfArangeException("至少买点吧། – _ – །");
}
else if(amount<=200) {
throw new AmountOutOfArangeException("不满足策略B实际情况!(ノ`⊿´)ノ");
}
else{
double money;
money = amount*0.85;
System.out.println("使用B策略实际花费"+money+"元");
}
}
}
- 折扣C
public class DiscountC implements Discount {
public void discount(double amount) throws AmountOutOfArangeException{
if(amount<=0){
throw new AmountOutOfArangeException("至少买点吧། – _ – །");
}
else if(amount<=200) {
throw new AmountOutOfArangeException("不如用策略A(°ー°〃)");
}
else{
double money;
money = 200+(amount-200)*0.7;
System.out.println("使用C策略实际花费"+money+"元");
}
}
}
折扣实现服务
public class DiscountService {
public void discountService(Discount discount, double amount) {
try {
discount.discount(amount);
} catch (AmountOutOfArangeException e) {
System.out.println("金额无效"+e.getMessage());
}catch (Exception e){
System.out.println("未知错误"+e.getMessage());
}
}
}
实践!
public class DiscountTest {
public static void main(String[] args) {
int amount;
String strategy;
Scanner scanner = new Scanner(System.in);
DiscountService discountpay = new DiscountService();
for(int i = 0;i < 5;i++){
System.out.println("请输入你的金额与你选择的折扣策略");
amount = scanner.next();
strategy = scanner.nextLine();
switch (strategy){
case("A")->{
discountpay.discountService(new DiscountA(),amount);
}
case("B")->{
discountpay.discountService(new DiscountB(),amount);
}
case("C")->{
discountpay.discountService(new DiscountC(),amount);
}
}
}
}
}