正确封装数组集合
您好,我的任务是构建一个具有以下简介的应用程序。
实现一个接口,根据促销规则计算价格。
co = Checkout.new(promotional_rules)
co.scan(item)
co.scan(item)
price = co.total
本质上,根据制定的促销规则,某些商品会相应折扣。
我对我的代码有一些反馈,指出我已经封装了 Promotion_rules 组,然后将规则公开为数组 - 糟糕的 OO
我最初创建了一个 Promotion_rules 对象,其中包含一组规则。
def initialize
@rules = []
end
def addrule(rule)
@rules.push(rule)
end
然后,在我的结帐对象中,我有已设置并传递到初始值设定项的 Promotion_rules 对象。我循环遍历促销规则对象中包含的规则数组,并将它们应用到结帐对象扫描的项目。
def initialize(promotionalrules=Promotionalrules.new)
@promotionalrules = promotionalrules
end
....Other code
for rule in @promotionalrules.getrules
for item in @items
##Execute rule on current item.
end
end
我对我的代码不太满意......循环与循环等。但我只是在寻找一些封装方面的帮助,因为我不确定我哪里出了问题。
任何关于应用于简报的良好设计模式的建议也会是有益的,因为我对我所采取的方法不太有信心。谢谢
Hi I was tasked with building an app with the following brief.
Implement an interface, which calculates prices based on promotional rules.
co = Checkout.new(promotional_rules)
co.scan(item)
co.scan(item)
price = co.total
Essentially, depending on the promotional rules set up, certain items are discounted accordingly.
I had some feedback on my code stating that I have encapsulated the group of promotional_rules and then exposed the rules as an array anyway - bad OO
I initially created a promotional_rules object, which contains an array of rules.
def initialize
@rules = []
end
def addrule(rule)
@rules.push(rule)
end
Then in my checkout object I have the promotional_rules object that has been setup and passed into the initializer. I loop through the array of rules contained in the promotional_rules object and apply them to the items scanned by the checkout object.
def initialize(promotionalrules=Promotionalrules.new)
@promotionalrules = promotionalrules
end
....Other code
for rule in @promotionalrules.getrules
for item in @items
##Execute rule on current item.
end
end
Im not overly happy with my code...the loop with the loop etc. But am just looking for some help with encapsulation as Im not sure where I have gone wrong.
Any suggestions on good design patterns to apply to the brief would be beneficial also, as not too confident about the approach I took. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜他们是在抱怨这种“暴露”:
这会将促销规则(可能应该称为促销规则)中的内部规则泄露给调用者。解决方法是稍微扭转你的逻辑:
然后:
本质的改变是你将规则集作为一个整体应用于每个项目。这隐藏了规则集实现细节,并且作为额外的好处,允许您轻松支持相互依赖的规则(“除非您使用优惠券 Y,否则您可以获得折扣 X”之类的东西)。
I'd guess that they're complaining about this "exposure":
that bleeds the internal rules from your Promotionalrules (which probably should be called PromotionalRules) out to the caller. The fix is to reverse your logic a little bit:
and then later:
The essential change is that you apply the ruleset as a whole to each item. This hides the ruleset implementation details and, as an extra bonus, allows you to easily support rules that depend on each other ("you can get discount X unless you're using coupon Y" and things like that).