为什么 Builder 模式比在创建的类对象中带有参数的构造函数更好?

发布于 2024-09-18 09:38:41 字数 155 浏览 2 评论 0原文

为什么我们不能在构造函数本身中使用不同的构建步骤。 如果构建步骤采用参数,为什么不能将它们作为参数提供给构造函数并在构造函数中使用来创建对象。

AFAIK,在Builder模式中,客户端要创建哪个特定对象;那么使用构建器而不是在正在创建的类对象中带有参数的构造函数有什么优势呢?

Why can we not the different build steps within the constructor itself.
if the build steps take arguments why can't they be provided as arguments to constructor and utilized within constructor to create the object.

AFAIK, in Builder pattern, the client which specific object to create; then what is the advantage in using a builder instead of a Constructor with arguments in the Class's object being created?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

浅唱々樱花落 2024-09-25 09:38:41

哦!我得到它。我正在查看维基百科的示例,并意识到为什么 Builder 很有帮助。当客户端不知道将哪些参数传递给构造函数时,这是很有帮助的,因为它非常复杂,因此无法直接调用构造函数并获取对象。因此,他向具体构建者寻求帮助,他们知道将哪些参数传递给构造函数,从而创建对象。

基本上,如果客户端是主要将参数传递给创建对象的类的构造函数的人,那么 Builder 就没那么有用了。使用原型也许更好。另一方面,如果有一小部分有限的特定对象可以通过将参数传递给该类的构造函数(或调用 setter)来创建,并且它们是经常使用的对象,那么最好封装此参数,将 thingy 传递到 Builder 类中,并使用它们为您创建对象。

Oh! I get it. I was looking at the Wikipedia example and realized why Builder is helpful. It is helpful, when the client does not know which arguments to pass to the constructor as it is very complicated and hence cannot call the constructor directly and get the object. Consequently, he asks for help from the Concrete Builders who know what arguments to pass to constructors and hence get the object created.

Basically, if the client is the one who is mostly going to be passing the arguments to the constructor of the Class whose object is created, then Builder is not that helpful. It is perhaps better to use the prototype. On the other hand, if there is a small finite set of specific objects that can be created from the class by passing arguments to the constructor (or calling setters) to that class and if they are the ones that are frequently used, then it better to encapsulate this argument passing thingy in the Builder class and use them to create the objects for you.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文