C++责任链模式实现折扣功能时最终返回未打折原价问题排查
问题根因
你的代码核心问题是责任链下游节点的计算结果没有被上游节点接收返回,实际执行流程如下:
- 主函数调用
fixated1->countDiscount(basket),在该函数内计算得到总价120,120<150不满足当前折扣条件,进入else if (next != NULL)分支,调用fixated2->countDiscount(basket) fixated2的函数内计算总价120,满足满100减15的条件,计算得到105、打印日志后返回105- 但返回到
fixated1的调用位置后,你没有接收这个105的返回值,代码继续执行到fixated1的return totalPrice语句,返回的是fixated1中最初计算的未打折总价120,这就是你拿到错误结果的原因。
修复方案
修改FixatedDiscount.cpp中的countDiscount函数,在调用下一个折扣节点时,直接返回下游节点的计算结果即可:
#include "FixatedDiscount.h" #include <iostream> int FixatedDiscount::countDiscount(Basket b) { int totalPrice = b.countPrice(); if (totalPrice >= limit) { totalPrice -= discount; std::cout << "Handled when limit is " << limit << " and discount is: " << discount << " returning total price: " << totalPrice << std::endl; return totalPrice; } else if (next != NULL) { // 直接返回下游节点的计算结果 return next->countDiscount(b); } else { std::cout << "I am the last handler, no discount applied" << std::endl; return totalPrice; } }
可选优化建议
- 总价不需要在每个折扣节点重复调用
b.countPrice()计算,可以作为参数在责任链中传递,减少重复计算开销 - 如果后续需要支持多折扣叠加,只需修改逻辑为命中当前折扣后,将计算后的价格传递给下一个节点继续判断即可,不需要终止链条
内容的提问来源于stack exchange,提问作者Aldomond
相关产品推荐
相关产品推荐

