gpt4 book ai didi

language-agnostic - 你会在哪里使用构建器模式而不是抽象工厂?

转载 作者:行者123 更新时间:2023-12-03 11:23:35 25 4
gpt4 key购买 nike

我已经多次看到这个问题出现在这里和那里,但我从未找到并回答我满意的答案。

来自维基百科:

Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.



但是对于客户来说不是一样的吗?一旦构建完成,他就会获得完整的对象,因此对他来说没有额外的功能。

我认为它的唯一方法是作为一种方式或逐步组织构造函数代码,以强制构建构建器实现的结构。这很好,但与抽象工厂相差甚远。

来自 Wikipedia 的下一点是一个很好的引用,可以说明我的观点:

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.



如果是这样,那么在您从抽象工厂转变为构建器的系统中必须引入什么样的复杂性?

我的观点是,我找不到一个很明显抽象工厂不够用的例子,而你需要一个 Builder。

最佳答案

AbstractFactory 适用于一系列相关产品。 Builder 适用于一种产品。

Builder 用于逐步构建复杂的产品,而 AbstractFactory 则以抽象的方式(即一次用于多个实现)构建不太复杂的产品。

差异对调用代码意味着什么的示例:

  • 对于使用 AbstractFactory 的客户端代码,每个方法调用构建一个对象。客户必须将它们组装在一起 .另一方面,构建器将在内部组装它们,并将完整的对象图作为构建的最后一步。
  • 构建器允许为客户端代码一一传递和检查参数。但是他可以一步构建最终产品(例如,调用构造函数,一次传递所有参数,甚至是自己构建的复杂参数)。所以构建器的产品可以是不可变对象(immutable对象)(或图形) (出于性能和内存原因,这在多线程环境中是无价的)。


  • 更新 回应此评论:

    Lino > It's still bothering me, though :). I mean, if you are building composite objects, and you take the director out, passing the responsibility of calling the builder methods to the clients, then it works for me. Only then the builder would seem a perfect fit. But with the director, it doens't seem like much...



    确切的说,Builder没有导演,它让每个客户 根据特定需求创建复杂产品 .客户是导演,因为导演的实现没有被重用。

    If you need to reuse a few times a complex building process, then you can have a method to encapsulate this (and this method is your "director").



    相反,对于 AbstractFactory,您通常需要 可重复使用的 Director,可创建类似的产品 (提供了工厂实现)。

    关于language-agnostic - 你会在哪里使用构建器模式而不是抽象工厂?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1946918/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com