如何高效实现多类商品的差异化折扣计算?
商品折扣计算代码优化方案
现有定义与规则
结构体定义
struct ProductDetails { string name; double actualPrice; double finalPrice; }product;
商品列表
- Apple(苹果)
- bag of Carrot(一袋胡萝卜)
- Orange(橙子)
- sale bag of beans(促销装豆子)
- cake(蛋糕)
- sale bag of grapes(促销装葡萄)
- cookie(饼干)
折扣规则
- 果蔬类商品享2%基础折扣,其他商品享4%基础折扣
- 名称以
sale开头的商品,在分类基础折扣之上额外享受10%折扣
折扣函数模板
// 参数说明:原价、基础折扣百分比、额外折扣百分比 double discount(double op, float dp=0.0, float additional=0.0) { // 计算折扣并返回最终价格 }
现有问题代码片段
这段代码存在硬编码、扩展性差、语法错误等问题:
// 代码片段 { std::vector<ProductDetails> itemsV; // 此处为获取所有ProductDetails的逻辑 itemsV.push_back(product); for(auto &item: itemsV) { if(item.name == ("Apple" || "bag of Carrot" || "Orange")) { item.finalPrice = discount(item.price,2,0); } else if(item.name == ("sale bag of beans" || "sale bag of grapes")) { item.finalPrice = discount(item.price,2,10); } else { item.finalPrice = discount(item.price,4,0); } // 后续对finalPrice的处理逻辑 } }
优化方案
1. 完善折扣计算函数
先实现正确的折扣计算逻辑:
double discount(double originalPrice, float baseDiscountPercent = 0.0, float additionalDiscountPercent = 0.0) { // 先算基础折扣后价格 double priceAfterBase = originalPrice * (100.0 - baseDiscountPercent) / 100.0; // 再叠加额外折扣 double finalPrice = priceAfterBase * (100.0 - additionalDiscountPercent) / 100.0; return finalPrice; }
2. 抽象分类与促销判断逻辑
把商品分类、促销标识的判断抽成独立函数,避免硬编码:
// 判断是否为果蔬类商品 bool isFruitVegetable(const std::string& productName) { // 用哈希集合存储,查询高效,后续新增商品只需修改集合 static const std::unordered_set<std::string> fvItems = { "Apple", "bag of Carrot", "Orange", "sale bag of beans", "sale bag of grapes" }; return fvItems.count(productName) > 0; } // 判断是否为促销商品(名称以"sale"开头) bool isSaleItem(const std::string& productName) { return productName.size() >= 4 && productName.substr(0, 4) == "sale"; }
3. 重构核心计算逻辑
利用上面的工具函数,简化循环内的判断,提升扩展性:
{ std::vector<ProductDetails> itemsV; // 获取所有ProductDetails的逻辑 for(auto &item: itemsV) { float baseDiscount = isFruitVegetable(item.name) ? 2.0f : 4.0f; float additionalDiscount = isSaleItem(item.name) ? 10.0f : 0.0f; // 修正原代码的字段错误:误用item.price,应为item.actualPrice item.finalPrice = discount(item.actualPrice, baseDiscount, additionalDiscount); // 后续对finalPrice的处理逻辑 } }
4. 进阶优化:配置化管理商品分类
如果商品列表频繁变动,可以把分类信息放到配置文件(如JSON)中,程序启动时加载,彻底摆脱硬编码:
// 从配置文件加载果蔬类商品列表 std::unordered_set<std::string> loadFruitVegetableItems(const std::string& configPath) { std::unordered_set<std::string> items; // 示例:读取JSON配置文件中的商品列表数组 // 此处省略文件读取、JSON解析的具体实现 return items; } // 全局维护分类集合,程序启动时加载一次 static const std::unordered_set<std::string> fvItems = loadFruitVegetableItems("./product_config.json"); bool isFruitVegetable(const std::string& productName) { return fvItems.count(productName) > 0; }
内容的提问来源于stack exchange,提问作者Falcon
相关产品推荐
相关产品推荐

