java使用策略模式优化代码中的if-else if 判断。

        首先,定义策略接口和不同的策略实现类:

// 策略接口
public interface DiscountStrategy {
    double applyDiscount(double originalPrice);
}

// 学生折扣策略
@Component
public class StudentDiscountStrategy implements DiscountStrategy {
    @Override
    public double applyDiscount(double originalPrice) {
        // 学生折扣为 10%
        return originalPrice * 0.9;
    }
}

// 老年人折扣策略
@Component
public class SeniorCitizenDiscountStrategy implements DiscountStrategy {
    @Override
    public double applyDiscount(double originalPrice) {
        // 老年人折扣为 15%
        return originalPrice * 0.85;
    }
}

// 普通顾客无折扣策略
@Component
public class NoDiscountStrategy implements DiscountStrategy {
    @Override
    public double applyDiscount(double originalPrice) {
        // 普通顾客无折扣
        return originalPrice;
    }
}

在上述代码中,使用了 @Component 注解来将每个折扣策略实现类声明为 Spring 管理的 Bean。

接下来,创建一个服务类,用于根据条件选择合适的折扣策略,并注入对应的策略 Bean:

@Service
public class DiscountService {
    
    @Autowired
    private StudentDiscountStrategy studentDiscountStrategy;
    
    @Autowired
    private SeniorCitizenDiscountStrategy seniorCitizenDiscountStrategy;
    
    @Autowired
    private NoDiscountStrategy noDiscountStrategy;
    
    public double calculateDiscountedPrice(double originalPrice, String customerType) {
        DiscountStrategy strategy = getDiscountStrategy(customerType);
        return strategy.applyDiscount(originalPrice);
    }
    
    private DiscountStrategy getDiscountStrategy(String customerType) {
        switch (customerType) {
            case "student":
                return studentDiscountStrategy;
            case "senior":
                return seniorCitizenDiscountStrategy;
            default:
                return noDiscountStrategy;
        }
    }
}

DiscountService 中,我们通过 @Autowired 注解将各种折扣策略注入到服务类中,并根据客户类型选择合适的策略。

最后,可以在控制器(Controller)或其他服务中使用 DiscountService

@RestController
@RequestMapping("/discount")
public class DiscountController {

    @Autowired
    private DiscountService discountService;

    @GetMapping("/calculate")
    public String calculateDiscount(@RequestParam String customerType, @RequestParam double originalPrice) {
        double discountedPrice = discountService.calculateDiscountedPrice(originalPrice, customerType);
        return "Discounted price for " + customerType + ": " + discountedPrice;
    }
}

在这个示例中,DiscountController 中的 calculateDiscount 方法接收客户类型和原始价格作为参数,并调用 DiscountServicecalculateDiscountedPrice 方法来计算折扣后的价格。

通过这种方式,你可以利用 Spring Boot 的依赖注入和管理功能,避免了使用大量的 if-else if 结构,使得代码更加清晰、灵活和可维护。

点点赞点点关注呀,持续分享有用的知识........................ 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值