假设我们有一个领域对象和这个对象的评估类。例如,在单独的类中的促销及其评估逻辑:
class BuyXGetYFreePromotion extends AbstractPromotion{
String x;
String y;
}
class BuyXGetYFreePromotionEvaluation {
public void evaluate(Cart cart){
for(String product : cart.getProducts()){
if(product.equal(BuyXGetYFreePromotion.x)){
//some code to discount y price
}
}
}
}
另一个例子:
class FixedPricePromotion extends AbstractPromotion{
String product;
Double price;
}
class FixedPricePromotionEvaluation {
public void evaluate(Cart cart){
for(String product : cart.getProducts()){
if(product.equal(FixedPricePromotion.product)){
//some code to discount y price
}
}
}
}
我们有很多这样的对子。
我们不能在域对象中注入评估,但我们可以将它们关联到评估类或其他类中。
第一个选项是将它们与 instanceof 语句相关联。
例如:
class PromotionService {
void evaluation(Cart cart){
for(AbstractPromotion p : getPromotions){
if(p instanceof BuyXGetYFreePromotion)
BuyXGetYFreePromotionEvaluation.evaluate(cart);
else if(p instanceof FixedPricePromotion)
FixedPricePromotionEvaluation.evaluate(cart);
}
}
}
但是这个例子违反了开闭原则。
我的问题是,我应该如何通过考虑 SOLID 原则来耦合这些对。
犯罪嫌疑人X
紫衣仙女
随时随地看视频慕课网APP
相关分类