第3篇:手写促销策略引擎(满减、打折、立减)

第3篇:手写促销策略引擎(满减、打折、立减)

摘要:本文用完整的代码实现电商促销策略引擎,从抽象策略到具体策略再到上下文,带你亲手写出第一个策略模式。

本文是《Java 23 种设计模式:从踩坑到精通》策略模式长文的扩充短文第3篇,帮助你碎片化掌握核心知识点。


1. 抽象策略

java 复制代码
public interface PromotionStrategy {
    double calculate(Order order);
}

所有促销策略都必须能"算钱"。

2. 具体策略

java 复制代码
public class FullReductionStrategy implements PromotionStrategy {
    @Override
    public double calculate(Order order) {
        double discount = Math.floor(order.getTotal() / 200) * 50;
        System.out.println("应用满减策略:满200减50,减免" + discount + "元");
        return order.getTotal() - discount;
    }
}

public class DiscountStrategy implements PromotionStrategy {
    @Override
    public double calculate(Order order) {
        System.out.println("应用打折策略:8折");
        return order.getTotal() * 0.8;
    }
}

public class DirectReductionStrategy implements PromotionStrategy {
    @Override
    public double calculate(Order order) {
        System.out.println("应用立减策略:立减30元");
        return order.getTotal() - 30;
    }
}

每种促销是一个独立的类,互不干扰,修改满减逻辑不会影响打折。

3. 上下文:订单结算

java 复制代码
public class Order {
    private double total;
    private PromotionStrategy strategy;

    public Order(double total) { this.total = total; }
    public double getTotal() { return total; }

    public void setPromotionStrategy(PromotionStrategy strategy) {
        this.strategy = strategy;
    }

    public double checkout() {
        if (strategy == null) {
            return total;
        }
        return strategy.calculate(this);
    }
}

订单不关心用哪种促销,它只知道有促销就用促销算钱,没有就原价。

4. 客户端

java 复制代码
Order order = new Order(500);
order.setPromotionStrategy(new FullReductionStrategy());
System.out.println("实付金额:" + order.checkout());

新增一种促销(如"赠品策略"),只需新增一个 GiftStrategy类,客户端注入即可,订单结算代码零修改


你的场景该不该手写代码?
判断标准 是 → 手写练习 否 → 理解概念即可
想真正掌握模式的使用
准备面试手撕代码
时间紧张,先了解思想 看代码示例即可

一句话总结:动手写一遍,胜过看十遍。策略模式的代码非常简洁,值得亲自敲一次。


📖 完整长文入口:本文是策略模式扩充系列的第3篇。如果你想一次性阅读完整内容(含UML、完整代码、框架应用、面试追问等),请查看原长文:

👉 《Java 23 种设计模式:从踩坑到精通 | 策略模式》

🔗 系列导航:

相关推荐
珍珠先生3 分钟前
P11 · MySQL 驱动版本过旧:Client does not support authentication protocol
java
~木雨12 分钟前
Java 并发编程架构全景:并发层的五域设计 —— 线程模型、线程池隔离、并发安全到问题治理(全体系汇总)
java·安全·架构·线程池·并发编程·高并发架构
极小狐30 分钟前
从复制粘贴到可复用组件:极狐GitLab CI/CD 组件目录实战
java·ci/cd·gitlab·devops·组件化
麻瓜code35 分钟前
【Agent】Spring AI RAG 实战:本地向量库 + 云端知识库
java·人工智能·spring
码匠许师傅1 小时前
【设计模式精讲】24.观察者模式(Observer)
c++·观察者模式·设计模式·uml
小刘在重生~1 小时前
Java 集合|Collection、List、ArrayList、LinkedList、泛型、Collections 工具类
java·数据结构·list
我不会起名字3221 小时前
一天一道算法题(29):单调栈
java·数据结构·python·算法·leetcode·golang·单调栈
XR1234567881 小时前
医院移动医护零漫游无线网络选型指南
java·后端·struts
干到60岁退休的码农1 小时前
13.构建登录接口响应数据
java·spring boot·mybatis
水巷石子2 小时前
学习langChain4j的第二天,体验springBoot中的starter
java·spring boot·学习·spring·langchain4j