Builder Vs装饰图案 [英] Builder Vs Decorator pattern

查看:106
本文介绍了Builder Vs装饰图案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候使用Builder模式?



据说构建器模式适用于比萨饼示例。



为什么不装饰?
通过处理奶酪,Pepperoni,培根作为基础比萨饼上的额外装饰。



是因为必须单独制作奶酪/胡椒粉。我不认为,他们需要单独建造,因为他们可以现成的。



请详细说明。
我也在寻找一个很好的现实世界的装饰师模式的例子,以及为什么它是适合这个特定例子的原因。谢谢。

解决方案

从维基百科的装饰模式文章:


在面向对象编程中,
装饰器模式是一种设计模式
,允许将新的/额外的行为
动态添加到现有对象


在完全构建比萨后,无需添加浇头。你不要吃半个比萨饼,然后再添加一个比萨饼。



换句话说,Builder Pattern使得很容易构建一个可独立扩展的对象方向在施工时间,而装饰图案允许您在施工时间后向对象添加扩展功能。使用装饰器模式来构造对象是不好的,因为它使对象保持不一致(或至少是不正确的)状态,直到所有必需的装饰器都到位 - 类似于使用setter指定可选构造函数参数的JavaBean问题。 >

From When would you use the Builder Pattern?,

It is said that builder pattern is appropriate for Pizza example.

Why not Decorator ? by treating Cheese, Pepperoni, Bacon as additional decorations on a base pizza.

Is it for the reason that Cheese/Pepperoni have to be built seperately. I don't think, they need to be built seperately as they can be available readymade.

Pls clarify. Am also looking for a good real-world example of decorator pattern and reason why it is the apt for that particular example. Thank you.

解决方案

From wikipedia's decorator pattern article:

In object-oriented programming, the decorator pattern is a design pattern that allows new/additional behaviour to be added to an existing object dynamically.

There's no need to add toppings to a Pizza after it has been fully constructed. You don't eat half a pizza and then add another topping to it.

In other words, the Builder Pattern makes it easy to construct an object which is extensible in independent directions at construction time, while the Decorator Pattern lets you add extensions to functionality to an object after construction time. Using the decorator pattern to construct objects is bad because it leaves the object in an inconsistent (or at least incorrect) state until all the required decorators are in place - similar to the JavaBean problem of using setters to specify optional constructor arguments.

这篇关于Builder Vs装饰图案的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆