何时适合为对象创建装饰器,何时适合重写对象以允许应用策略?
例如,假设我有一个可以添加到购物车的 Product 类。我可能希望能够将它与购物车中的其他商品一起打包并添加 15% 的折扣。
产品类是否应该用允许交易的新子类进行装饰,或者是否应该重新设计产品类以允许购物车将降价“策略”对象附加到产品上,从而降低价格?
这是一个抽象的例子,所以你可以随意使用。
For example, suppose I have a Product class that I can add to a shopping cart. I may want to be able to package it together with another item when it is also in the cart and add a 15% discount.
Should the product class be decorated with a new subclass allowing deals, or should product class be redesigned to allow the cart attach a price reduction "strategy" object to the Product, reducing the price?
This is an abstract example, so take it where you will.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
装饰器是您可以应用的侵入性最小的模式之一 - 当您这样做时,您遵循开放/关闭原则,因为您的原始类永远不会被修改。我倾向于尽可能使用装饰器。当原始类不需要与扩展交互时,通常会出现这种情况。
注入策略更具侵入性,因为必须修改获取策略的类才能接受该策略(显然,一旦进行了此修改,您就可以应用许多不同的策略,而无需进一步修改您的类)。当原始类需要与策略交互时(例如询问某事),我使用策略。
请注意,策略通常可以被修饰......
Decorator is one of the least invasive patterns you can apply - when you do so, you follow the Open/Closed Principle because your original class is never modified. I tend to use Decorator whenever possible. This is mostly the case when the original class doesn't need to interact with the extension.
Injecting a Strategy is more invasive because the class getting the Strategy must be modified to accept the Strategy (obviously, once you have made this modification, you can apply lots of different Strategies without further modifying your class). I use Strategy when the original class needs to interact with the Strategy (e.g. ask it about something).
Note that Strategies can often be Decorated...
只需查看您的域名即可。
如果它是允许降价的产品(嗯......我不这么认为)那么你应该将它添加到产品中。
如果是订单(在我看来,是打折的正确地方),那么它应该在那里。
just look at your domain.
if it is product which allows its price reduction (hm... i don't think so) then you should add it to product.
if it is order (imo, the right place to do discounts) then it should be there.