建造者设计模式和工厂设计模式有什么区别?

发布于 2024-07-17 09:05:35 字数 1436 浏览 12 评论 0原文

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

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

发布评论

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

评论(27

浅唱ヾ落雨殇 2024-07-24 09:05:35

对于设计模式,通常没有适用于所有情况的“更有利”的解决方案。 这取决于您需要实施什么。

来自维基百科:

  • Builder 专注于构建
    逐步复杂的对象。 抽象的
    工厂强调产品系列
    对象(简单或复杂)。
    建造者返回产品作为最终产品
    步骤,但就摘要而言
    工厂关注,产品得到
    立即返回。
  • Builder 经常构建 Composite。
  • 通常,设计是从工厂方法开始的(不太复杂,更多
    可定制,子类激增)
    并向抽象工厂演进,
    原型,或构建器(更灵活,
    更复杂)作为设计师
    发现哪里更有灵活性
    需要。
  • 有时创建模式是互补的:构建者可以使用一种模式
    要实现的其他模式
    构建了哪些组件。 抽象的
    工厂、构建器和原型可以
    在他们的中使用 Singleton
    实现。

工厂设计模式的维基百科条目:
http://en.wikipedia.org/wiki/Factory_method_pattern

构建器设计模式的 Wikipedia 条目:
http://en.wikipedia.org/wiki/Builder_pattern

With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.

From Wikipedia:

  • 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.
  • Builder often builds a Composite.
  • 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.
  • Sometimes creational patterns are complementary: Builder can use one
    of the other patterns to implement
    which components get built. Abstract
    Factory, Builder, and Prototype can
    use Singleton in their
    implementations.

Wikipedia entry for factory design pattern:
http://en.wikipedia.org/wiki/Factory_method_pattern

Wikipedia entry for builder design pattern:
http://en.wikipedia.org/wiki/Builder_pattern

怀念你的温柔 2024-07-24 09:05:35

工厂只是构造函数(可能是不同类中的一个)的包装函数。 关键区别在于工厂方法模式要求在单个方法调用中构建整个对象,并在一行中传递所有参数。 最终的对象将被返回。

另一方面,构建器模式本质上是一个包装器对象,它围绕您可能想要传递到构造函数调用中的所有可能参数。 这允许您使用 setter 方法来慢慢构建参数列表。 构建器类上的另一种方法是 build() 方法,该方法只需将构建器对象传递到所需的构造函数中,然后返回结果。

在像 Java 这样的静态语言中,当您有多个(可能是可选的)参数时,这一点变得更加重要,因为它避免了为所有可能的参数组合使用伸缩构造函数的要求。 此外,构建器允许您使用 setter 方法来定义在调用构造函数后无法直接修改的只读或私有字段。

基本工厂示例

// Factory
static class FruitFactory {
    static Fruit create(name, color, firmness) {
        // Additional logic
        return new Fruit(name, color, firmness);
    }
}

// Usage
Fruit fruit = FruitFactory.create("apple", "red", "crunchy");

基本构建器示例

// Builder
class FruitBuilder {
    String name, color, firmness;
    FruitBuilder setName(name)         { this.name     = name;     return this; }
    FruitBuilder setColor(color)       { this.color    = color;    return this; }
    FruitBuilder setFirmness(firmness) { this.firmness = firmness; return this; }
    Fruit build() {
        return new Fruit(this); // Pass in the builder
    }
}

// Usage
Fruit fruit = new FruitBuilder()
        .setName("apple")
        .setColor("red")
        .setFirmness("crunchy")
        .build();

比较这两个维基百科页面的代码示例可能是值得的:

http://en.wikipedia.org/wiki/Factory_method_pattern
http://en.wikipedia.org/wiki/Builder_pattern

A factory is simply a wrapper function around a constructor (possibly one in a different class). The key difference is that a factory method pattern requires the entire object to be built in a single method call, with all the parameters passed in on a single line. The final object will be returned.

A builder pattern, on the other hand, is in essence a wrapper object around all the possible parameters you might want to pass into a constructor invocation. This allows you to use setter methods to slowly build up your parameter list. One additional method on a builder class is a build() method, which simply passes the builder object into the desired constructor, and returns the result.

In static languages like Java, this becomes more important when you have more than a handful of (potentially optional) parameters, as it avoids the requirement to have telescopic constructors for all the possible combinations of parameters. Also a builder allows you to use setter methods to define read-only or private fields that cannot be directly modified after the constructor has been called.

Basic Factory Example

// Factory
static class FruitFactory {
    static Fruit create(name, color, firmness) {
        // Additional logic
        return new Fruit(name, color, firmness);
    }
}

// Usage
Fruit fruit = FruitFactory.create("apple", "red", "crunchy");

Basic Builder Example

// Builder
class FruitBuilder {
    String name, color, firmness;
    FruitBuilder setName(name)         { this.name     = name;     return this; }
    FruitBuilder setColor(color)       { this.color    = color;    return this; }
    FruitBuilder setFirmness(firmness) { this.firmness = firmness; return this; }
    Fruit build() {
        return new Fruit(this); // Pass in the builder
    }
}

// Usage
Fruit fruit = new FruitBuilder()
        .setName("apple")
        .setColor("red")
        .setFirmness("crunchy")
        .build();

It may be worth comparing the code samples from these two wikipedia pages:

http://en.wikipedia.org/wiki/Factory_method_pattern
http://en.wikipedia.org/wiki/Builder_pattern

眉黛浅 2024-07-24 09:05:35

Factory 模式几乎可以看作是 Builder 模式的简化版本。

工厂模式中,工厂负责根据需要创建对象的各种子类型。

工厂方法的用户不需要知道该对象的确切子类型。 工厂方法 createCar 的示例可能会返回 FordHonda 类型的对象。

Builder模式中,不同的子类型也由构建器方法创建,但同一子类中对象的组成可能不同。

要继续汽车示例,您可能有一个 createCar 构建器方法,该方法创建具有 4 缸发动机的 Honda 类型对象,或 Honda-有 6 个圆柱体的打字对象。 构建器模式允许这种更细的粒度。

构建器模式工厂方法模式可在维基百科上找到。

The Factory pattern can almost be seen as a simplified version of the Builder pattern.

In the Factory pattern, the factory is in charge of creating various subtypes of an object depending on the needs.

The user of a factory method doesn't need to know the exact subtype of that object. An example of a factory method createCar might return a Ford or a Honda typed object.

In the Builder pattern, different subtypes are also created by a builder method, but the composition of the objects might differ within the same subclass.

To continue the car example you might have a createCar builder method which creates a Honda-typed object with a 4 cylinder engine, or a Honda-typed object with 6 cylinders. The builder pattern allows for this finer granularity.

Diagrams of both the Builder pattern and the Factory method pattern are available on Wikipedia.

半步萧音过轻尘 2024-07-24 09:05:35

构建器设计模式描述了一个对象,该对象知道如何通过几个步骤制作另一个特定类型的对象。 它在每个中间步骤保存目标项所需的状态。 想想 StringBuilder 经历了什么才能生成最终的字符串。

工厂设计模式描述了一个对象,该对象知道如何一步创建几种不同但相关类型的对象,其中根据给定参数选择特定类型。 想想序列化系统,您可以在其中创建序列化程序,并在一次加载调用中构建所需的对象。

The builder design pattern describes an object that knows how to craft another object of a specific type over several steps. It holds the needed state for the target item at each intermediate step. Think what StringBuilder goes through to produce a final string.

The factory design pattern describes an object that knows how to create several different but related kinds of object in one step, where the specific type is chosen based on given parameters. Think of the serialization system, where you create your serializer and it constructs the desired in object all in one load call.

找个人就嫁了吧 2024-07-24 09:05:35
  • 逐步构建复杂对象:构建器模式

  • 使用单一方法创建简单对象:工厂方法模式

  • 使用多个工厂方法创建对象:抽象工厂模式

  • Constructing a complex object step by step : builder pattern

  • A simple object is created by using a single method : factory method pattern

  • Creating Object by using multiple factory method : Abstract factory pattern

标点 2024-07-24 09:05:35
BuilderFactory
仅返回单个实例来处理复杂的对象构造在多个构造函数上返回各种实例
不需要接口 涉及接口驱动的
内部类(以避免伸缩构造函数)涉及子类

伸缩构造函数模式

类比:

  • 工厂: 考虑一家餐厅。 “今天的饭菜”的创建是一种工厂模式,因为你告诉厨房“给我今天的饭菜”,厨房(工厂)根据隐藏的标准决定生成什么对象。
  • 生成器:如果您订购定制披萨,则会出现生成器。 在这种情况下,服务员告诉厨师(建造者)“我需要一个披萨;添加奶酪、洋葱和培根!” 因此,构建器公开了生成的对象应具有的属性,但隐藏了如何设置它们。

礼貌

BuilderFactory
Return only single instance to handle complex object constructionReturn various instances on multiple constructors
No interface requiredInterface driven
Inner classes is involved (to avoid telescopic constructors)Subclasses are involved

Telescoping Constructor Pattern

Analogy:

  • Factory: Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.
  • Builder: The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

Courtesy

天煞孤星 2024-07-24 09:05:35

建造者模式和工厂模式,从肉眼看来都非常相似,因为它们都为你创建对象。

但你需要仔细看看

这个现实生活中的例子会让两者之间的区别更加清晰。

假设您去了一家快餐店并点了食物

1)什么食物?

披萨

2)什么配料?

辣椒,番茄,烧烤鸡,没有菠萝

所以不同种类的食物是由工厂模式制作的,但特定食物的不同变体(口味)是由建造者模式制作的。

不同种类的食物

披萨、汉堡、面食

披萨的变种

仅披萨奶酪、奶酪+番茄+辣椒、奶酪+番茄等

。代码示例

您可以在此处查看两种模式的示例代码实现
构建器模式
工厂模式

Builder Pattern and Factory pattern, both seem pretty similar to naked eyes because they both create objects for you.

But you need to look closer

This real-life example will make the difference between the two more clear.

Suppose, you went to a fast food restaurant and you ordered Food.

1) What Food?

Pizza

2) What toppings?

Capsicum, Tomato, BBQ chicken, NO PINEAPPLE

So different kinds of foods are made by Factory pattern but the different variants(flavors) of a particular food are made by Builder pattern.

Different kinds of foods

Pizza, Burger, Pasta

Variants of Pizza

Only Cheese, Cheese+Tomato+Capsicum, Cheese+Tomato etc.

Code sample

You can see the sample code implementation of both patterns here
Builder Pattern
Factory Pattern

飘过的浮云 2024-07-24 09:05:35

两者都是创建模式,用于创建对象。

1) 工厂模式 - 假设您有一个超类和 N 个子类。
创建对象取决于传递哪个参数/值。

2) Builder模式——创建复杂的对象。

Ex: Make a Loan Object. Loan could be house loan, car loan ,
    education loan ..etc. Each loan will have different interest rate, amount ,  
    duration ...etc. Finally a complex object created through step by step process.

Both are Creational patterns, to create Object.

1) Factory Pattern - Assume, you have one super class and N number of sub classes.
The object is created depends on which parameter/value is passed.

2) Builder pattern - to create complex object.

Ex: Make a Loan Object. Loan could be house loan, car loan ,
    education loan ..etc. Each loan will have different interest rate, amount ,  
    duration ...etc. Finally a complex object created through step by step process.
一身软味 2024-07-24 09:05:35

首先遵循我的论点的一些一般性内容:

设计大型软件系统的主要挑战是它们必须灵活且易于更改。 因此,有一些指标,例如耦合度和内聚度。 为了实现可以轻松更改或扩展其功能而无需从头开始重新设计整个系统的系统,您可以遵循设计原则(如 SOLID 等)。 一段时间后,一些开发人员认识到,如果他们遵循这些原则,就会有一些类似的解决方案可以很好地解决类似的问题。 这些标准解决方案最终成为设计模式。

所以设计模式是为了支持你遵循通用的设计原则,以实现具有高内聚的松耦合系统。

回答问题:

通过询问两种模式之间的差异,您必须问自己哪种模式使您的系统以哪种方式更加灵活。 每个模式都有其自己的目的来组织系统中类之间的依赖关系。

抽象工厂模式:
GoF:“提供一个接口,用于创建相关或依赖对象系列,而无需指定它们的具体类。”

这是什么意思:
通过提供这样的接口,对每个系列产品的构造函数的调用都封装在工厂类中。 因为这是整个系统中唯一调用这些构造函数的地方,所以您可以通过实现新的工厂类来更改您的系统。 如果您通过另一个工厂交换工厂的表示,则可以交换整套产品,而无需触及大部分代码。

构建器模式:
GoF:“将复杂对象的构造与其表示分离,以便相同的构造过程可以创建不同的表示。”

这是什么意思:
您将构造过程封装在另一个类中,称为导演(GoF)。 该控制器包含创建产品新实例的算法(例如,用其他部分组成一个复杂的产品)。 为了创建整个产品的组成部分,导演使用了构建器。 通过交换director中的构建器,您可以使用相同的算法来创建产品,但更改单个零件的表示(以及产品的表示)。 要扩展或修改产品表示中的系统,您所需要做的就是实现一个新的构建器类。

简而言之:
抽象工厂模式的目的是交换一组可以一起使用的产品。 构建器模式的目的是封装创建产品的抽象算法,以便将其重用于产品的不同表示形式。

在我看来,你不能说抽象工厂模式是建造者模式的老大哥。 是的,它们都是创造模式,但模式的主要意图完全不同。

First some general things to follow my argumentation:

The main challenge in designing big software systems is that they have to be flexible and uncomplicated to change. For this reason, there are some metrics like coupling and cohesion. To achieve systems that can be easily altered or extended in its functionality without the need to redesign the whole system from scratch, you can follow the design principles (like SOLID, etc.). After a while some developer recognized that if they follow those principles there are some similar solutions that worked well to similar problems. Those standard solutions turned out to be the design patterns.

So the design patterns are to support you to follow the general design principles in order to achieve loosely coupled systems with high cohesion.

Answering the question:

By asking the difference between two patterns you have to ask yourself what pattern makes your system in which way more flexible. Each pattern has its own purpose to organize dependencies between classes in your system.

The Abstract Factory Pattern:
GoF: “Provide an interface for creating families of related or dependent objects without specifying their concrete classes.”

What does this mean:
By providing an interface like this the call to the constructor of each of the family’s product is encapsulated in the factory class. And because this is the only place in your whole system where those constructors are called you can alter your system by implementing a new factory class. If you exchange the representation of the factory through another, you can exchange a whole set of products without touching the majority of your code.

The Builder Pattern:
GoF: “Separate the construction of a complex object from its representation so that the same construction process can create different representations.”

What does this mean:
You encapsulate the process of construction in another class, called the director (GoF). This director contains the algorithm of creating new instances of the product (e.g. compose a complex product out of other parts). To create the integral parts of the whole product the director uses a builder. By exchanging the builder in the director you can use the same algorithm to create the product, but change the representations of single parts (and so the representation of the product). To extend or modify your system in the representation of the product, all you need to do is to implement a new builder class.

So in short:
The Abstract Factory Pattern’s purpose is to exchange a set of products which are made to be used together. The Builder Pattern’s purpose is to encapsulate the abstract algorithm of creating a product to reuse it for different representations of the product.

In my opinion you can’t say that the Abstract Factory Pattern is the big brother of the Builder Pattern. YES, they are both creational patterns, but the main intent of the patterns is entirely different.

绿光 2024-07-24 09:05:35

工厂:用于创建对象的实例,其中对象的依赖关系完全由工厂保存。 对于抽象工厂模式来说,同一个抽象工厂通常有许多具体实现。 工厂的正确实现是通过依赖注入注入的。

Builder:用于构建不可变对象,当要实例化的对象的依赖关系部分预先已知且部分由客户端提供时建造者。

Factory: Used for creating an instance of an object where the dependencies of the object are entirely held by the factory. For the abstract factory pattern, there are often many concrete implementations of the same abstract factory. The right implementation of the factory is injected via dependency injection.

Builder: Used to build immutable objects, when the dependencies of the object to be instantiated are partly known in advance and partly provided by the client of the builder.

留蓝 2024-07-24 09:05:35

Builder 和 Builder 之间的一个显着区别 我可以看出的工厂如下

假设我们有一辆汽车

class Car
{
  bool HasGPS;
  bool IsCityCar;
  bool IsSportsCar;
  int   Cylenders;
  int Seats;

  public:
     void Car(bool hasGPs=false,bool IsCityCar=false,bool IsSportsCar=false, int Cylender=2, int Seats=4);
 };

在上面的界面中我们可以通过以下方式获得汽车:

 int main()
 {
    BadCar = new Car(false,false,true,4,4);
  }

但是如果在创建座位时发生一些异常怎么办???
你根本不会得到这个物体 //
但是

假设你有如下的实现

class Car
 {
    bool mHasGPS;
    bool mIsCityCar;
    bool mIsSportsCar;
    int mCylenders;
    int mSeats;

 public:
    void Car() : mHasGPs(false), mIsCityCar(false), mIsSportsCar(false), mCylender(2), mSeats(4) {}
    void SetGPS(bool hasGPs=false)  {mHasGPs = hasGPs;}
    void SetCity(bool CityCar)  {mIsCityCar = CityCar;}
    void SetSports(bool SportsCar)  {mIsSportsCar = SportsCar;}
    void SetCylender(int Cylender)  {mCylenders = Cylender;}    
    void SetSeats(int seat) {mSeats = seat;}    
};

 class CarBuilder 
 {
    Car* mCar;
public:
        CarBuilder():mCar(NULL) {   mCar* = new Car();  }
        ~CarBuilder()   {   if(mCar)    {   delete mCar;    }
        Car* GetCar()   {   return mCar; mCar=new Car();    }
        CarBuilder* SetSeats(int n) {   mCar->SetSeats(n); return this; }
        CarBuilder* SetCylender(int n)  {   mCar->SetCylender(n); return this;  }
        CarBuilder* SetSports(bool val) {   mCar->SetSports(val); return this;  }
        CarBuilder* SetCity(bool val)   {   mCar->SetCity(val); return this;    }
        CarBuilder* SetGPS(bool val)    {   mCar->SetGPS(val); return this; }
}

现在你可以像这样创建

 int main()
 {
   CarBuilder* bp =new CarBuilder;
    Car* NewCar  = bp->SetSeats(4)->SetSports(4)->SetCity(ture)->SetGPS(false)->SetSports(true)->GetCar();

     bp->SetSeats(2);

     bp->SetSports(4);

     bp->SetCity(ture);

     bp->SetSports(true)

     Car* Car_II=  bp->GetCar();

  }

在第二种情况下,即使一个操作失败你仍然会得到汽车。

也许那辆车以后不能完美工作,但是,你会得到这个对象。

因为工厂方法在一次调用中为您提供了汽车,而构建器则一一构建。

虽然,这取决于设计的需要。

One striking difference between Builder & factory which I could make out was the following

suppose we have a car

class Car
{
  bool HasGPS;
  bool IsCityCar;
  bool IsSportsCar;
  int   Cylenders;
  int Seats;

  public:
     void Car(bool hasGPs=false,bool IsCityCar=false,bool IsSportsCar=false, int Cylender=2, int Seats=4);
 };

In the above interface we can get car by the following way :

 int main()
 {
    BadCar = new Car(false,false,true,4,4);
  }

but what if, some exception happens while creating the Seats ???
YOU WILL NOT GET THE OBJECT AT ALL //
BUT

suppose you have implementation like the following

class Car
 {
    bool mHasGPS;
    bool mIsCityCar;
    bool mIsSportsCar;
    int mCylenders;
    int mSeats;

 public:
    void Car() : mHasGPs(false), mIsCityCar(false), mIsSportsCar(false), mCylender(2), mSeats(4) {}
    void SetGPS(bool hasGPs=false)  {mHasGPs = hasGPs;}
    void SetCity(bool CityCar)  {mIsCityCar = CityCar;}
    void SetSports(bool SportsCar)  {mIsSportsCar = SportsCar;}
    void SetCylender(int Cylender)  {mCylenders = Cylender;}    
    void SetSeats(int seat) {mSeats = seat;}    
};

 class CarBuilder 
 {
    Car* mCar;
public:
        CarBuilder():mCar(NULL) {   mCar* = new Car();  }
        ~CarBuilder()   {   if(mCar)    {   delete mCar;    }
        Car* GetCar()   {   return mCar; mCar=new Car();    }
        CarBuilder* SetSeats(int n) {   mCar->SetSeats(n); return this; }
        CarBuilder* SetCylender(int n)  {   mCar->SetCylender(n); return this;  }
        CarBuilder* SetSports(bool val) {   mCar->SetSports(val); return this;  }
        CarBuilder* SetCity(bool val)   {   mCar->SetCity(val); return this;    }
        CarBuilder* SetGPS(bool val)    {   mCar->SetGPS(val); return this; }
}

Now you can create like this

 int main()
 {
   CarBuilder* bp =new CarBuilder;
    Car* NewCar  = bp->SetSeats(4)->SetSports(4)->SetCity(ture)->SetGPS(false)->SetSports(true)->GetCar();

     bp->SetSeats(2);

     bp->SetSports(4);

     bp->SetCity(ture);

     bp->SetSports(true)

     Car* Car_II=  bp->GetCar();

  }

Here in the second case , even if one operation fails you would still get the Car.

May be that car does not works perfectly later but , you would have the object.

Because Factory Method gives you the Car in single call , whereas the Builder builds one by one.

Although, It depends on the needs of the deign which one to go for.

山川志 2024-07-24 09:05:35

与工厂模式相比,构建器模式的主要优点是,如果您想要创建一些具有大量可能的自定义项的标准对象,但您通常最终只会自定义一些内容。

例如,如果您想编写一个 HTTP 客户端 - 您将设置一些默认参数,例如默认写入/读取超时、协议、缓存、DNS、拦截器等。

您的客户端的大多数用户只会使用这些默认参数,而其他一些用户可能想要自定义一些其他参数。
在某些情况下,您只想更改超时并按原样使用其余部分,而在其他情况下,您可能需要自定义例如缓存。

以下是实例化客户端的可能方法(取自 OkHttpClient):

//just give me the default stuff
HttpClient.Builder().build()   

//I want to use custom cache
HttpClient.Builder().cache(MyCache()).build() 

//I want custom connection timeout
HttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).build() 

//I am more interested in read/write timeout
HttpClient.Builder()
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS).build()

如果您为此使用工厂模式,您最终将编写大量具有所有可能的创建参数组合的方法。
使用构建器,您只需指定您关心的参数,然后让构建器为您构建它,并处理所有其他参数。

The main advantage of the builder pattern over factory pattern is in case if you want to create some standard object with lots of possible customizations, but you usually end up customizing just a few.

For example, if you want to write an HTTP Client - you'll set up some default parameters like default write/read timeout, protocols, cache, DNS, interceptors, etc.

Most of the users of your client will just use those default parameters, while some other users might want to customize some of the other parameters.
In some cases, you'll just want to change timeouts and use the rest as it is, while in other cases you might need to customize for example the cache.

Here are possible ways of instantiating your client (taken from OkHttpClient):

//just give me the default stuff
HttpClient.Builder().build()   

//I want to use custom cache
HttpClient.Builder().cache(MyCache()).build() 

//I want custom connection timeout
HttpClient.Builder().connectTimeout(30, TimeUnit.SECONDS).build() 

//I am more interested in read/write timeout
HttpClient.Builder()
        .readTimeout(30, TimeUnit.SECONDS)
        .writeTimeout(30, TimeUnit.SECONDS).build()

If you'd use a factory pattern for this, you'll end up writing a lot of methods with all possible combinations of creational parameters.
With the builder, you just specify those you care about and let the builder build it for you taking care of all those other params.

白馒头 2024-07-24 09:05:35

Builder抽象工厂 有着不同的用途。 根据正确的用例,您必须选择合适的设计模式。

Builder 显着特征:

  1. Builder 模式使用简单对象并使用逐步方法构建复杂对象
  2. Builder 类逐步构建最终对象。 这个构建器独立于其他对象

工厂(简单工厂)显着特征:

  1. 创建模式
  2. 基于继承
  3. 工厂返回一个工厂方法(接口),该方法又返回具体对象

看看相关帖子:

将构建器保留在单独的类中(流畅的界面)

设计模式:工厂与工厂方法与抽象工厂

Builder and Abstract Factory have meant for different purposes. Depending on right use case, you have to select suitable design pattern.

Builder salient features:

  1. Builder pattern builds a complex object using simple objects and using a step by step approach
  2. A Builder class builds the final object step by step. This builder is independent of other objects

Factory (simple Factory) salient features:

  1. Creational pattern
  2. Based on inheritance
  3. Factory returns a Factory Method (interface) which in turn returns Concrete Object

Have a look at related posts:

Keeping builder in separate class (fluent interface)

Design Patterns: Factory vs Factory method vs Abstract Factory

卖梦商人 2024-07-24 09:05:35

抽象工厂与 构建器模式都是创建模式,但意图不同。

抽象工厂模式强调相关对象系列的对象创建,其中:

  • 每个系列都是从公共基类/接口派生的一组类。
  • 每个对象都会作为一次调用的结果立即返回。

构建器模式专注于逐步构建一个复杂的对象。
它将表示与构造复杂对象的过程解耦,以便相同的构造过程可以用于不同的表示。

  • Builder 对象封装了复杂对象的配置。
  • Director 对象知道使用 Builder 的协议,其中
    协议定义了构建复杂对象所需的所有逻辑步骤。

Abstract Factory & Builder pattern are both Creational patterns but with different intent.

Abstract Factory Pattern emphasizes object creation for families of related objects where:

  • Each family is a set of classes derived from a common base class/Interface.
  • Each object is returned immediately as a result of one call.

Builder pattern focuses on constructing a complex object step by step.
It decouples the representation from the process of constructing the complex object, so that the same construction process can be used for different representations.

  • Builder object encapsulates configuration of the complex object.
  • Director object knows the protocol of using the Builder, where the
    protocol defines all logical steps required to build the complex object.
趁年轻赶紧闹 2024-07-24 09:05:35

复杂构造是指要构造的对象由抽象表示的不同其他对象组成。

考虑一下麦当劳的菜单。 菜单包含饮品、主菜和配菜。 根据各个抽象的后代组合在一起,创建的菜单具有另一种表示形式。

  1. 示例:可乐、巨无霸、炸薯条
  2. 示例:雪碧、掘金、炸薯条

这里,我们得到了两个具有不同表示形式的菜单实例。 施工过程又保持不变。 您创建了一份包含饮品、主菜和配菜的菜单。

通过使用构建器模式,您可以将创建复杂对象的算法与用于创建它的不同组件分开。

就构建器模式而言,算法被封装在控制器中,而构建器用于创建不可或缺的部分。 改变导演算法中使用的构建器会导致不同的表示,因为其他部分组成了菜单。 创建菜单的方式保持不变。

A complex construction is when the object to be constructed is composed of different other objects which are represented by abstractions.

Consider a menu in McDonald's. A menu contains a drink, a main and a side. Depending on which descendants of the individual abstractions are composed together, the created menu has another representation.

  1. Example: Cola, Big Mac, French Fries
  2. Example: Sprite, Nuggets, Curly Fries

There, we got two instances of the menu with different representations. The process of construction in turn remains the same. You create a menu with a drink, a main and a side.

By using the builder pattern, you separate the algorithm of creating a complex object from the different components used to create it.

In terms of the builder pattern, the algorithm is encapsulated in the director whereas the builders are used to create the integral parts. Varying the used builder in the algorithm of the director results in a different representation because other parts are composed to a menu. The way a menu is created remains the same.

倾城花音 2024-07-24 09:05:35

它们之间的主要区别在于,Builder 模式主要描述了逐步创建复杂对象的过程。 在抽象工厂模式中,重点是对象-产品系列。 Builder 在最后一步返回产品。 在抽象工厂模式中,产品立即可用

例子:
假设我们正在创建迷宫

1。 抽象工厂:

Maze* MazeGame::CreateMaze (MazeFactory& factory) {
Maze* maze = factory.MakeMaze(); /// product is available at start!!
 /* Call some methods on maze */
return maze;
}

2。 建造者:

Maze* MazeGame::CreateMaze (MazeBuilder& builder) {
builder.buildMaze(); /// We don't have access to maze
 /* Call some methods on builder */
return builder.GetMaze();
}

The main difference between them is that the Builder pattern primarily describes the creation of complex objects step by step. In the Abstract Factory pattern, the emphasis is on families of objects-products. Builder returns the product in the last step. While in the Abstract Factory pattern the product is available immediately.

Example:
Let say that we are creating Maze

1. Abstract Factory:

Maze* MazeGame::CreateMaze (MazeFactory& factory) {
Maze* maze = factory.MakeMaze(); /// product is available at start!!
 /* Call some methods on maze */
return maze;
}

2. Builder:

Maze* MazeGame::CreateMaze (MazeBuilder& builder) {
builder.buildMaze(); /// We don't have access to maze
 /* Call some methods on builder */
return builder.GetMaze();
}
太傻旳人生 2024-07-24 09:05:35

这两种模式都有相同的必要性:向某些客户端代码隐藏复杂对象的构造逻辑。 但是是什么让一个对象变得“复杂”(或者有时,变得复杂)呢? 主要是由于依赖关系,或者更确切地说是由更多部分状态组成的对象的状态。 您可以通过构造函数注入依赖项来设置初始对象状态,但是一个对象可能需要很多依赖项,其中一些将处于默认初始状态(只是因为我们应该知道将默认依赖项设置为 null 并不是最干净的方法)和其他一些设置为由某些条件驱动的状态。 此外,有些对象属性是某种“不经意的依赖关系”,但它们也可以呈现可选状态。

有两种众所周知的方法可以控制这种复杂性:

  • 组合/聚合:构造一个对象,构造其依赖对象,然后连接在一起。 在这里,构建器可以使确定引导组件构造的规则的过程变得透明和灵活。

  • 多态性:构造规则直接声明到子类型定义中,因此每个子类型都有一组规则,并且某些条件决定这组规则中的哪一个适用于构造对象。 工厂非常适合这种情况。

没有什么可以阻止这两种方法的混合。 产品系列可以抽象使用构建器完成的对象创建,构建器可以使用工厂来确定实例化哪个组件对象。

Both patterns come for the same necessity: Hide from some client code the construction logic of a complex object. But what makes "complex" (or, sometimes, complicate) an object? Mainly, it's due to dependencies, or rather the state of an object composed by more partial states. You can inject dependencies by constructor to set the initial object state, but an object may require a lot of them, some will be in a default initial state (just because we should have learned that set a default dependency to null is not the cleanest way) and some other set to a state driven by some condition. Moreover, there are object properties that are some kind of "oblivious dependencies" but also they can assume optional states.

there are two well known ways to dominate that complexity:

  • Composition/aggregation: Construct an object, construct its dependent objects, then wire together. Here, a builder can make transparent and flexible the process that determines the rules that lead the construction of component.

  • Polymorphism: Construction rules are declared directly into subtype definition, so you have a set of rules for each subtype and some condition decides which one among these set of rules apply to construct the object. A factory fits perfectly in this scenario.

Nothing prevents to mix these two approaches. A family of product could abstract object creation done with a builder, a builder could use factories to determine which component object instantiate.

抽个烟儿 2024-07-24 09:05:35

我相信,Factory 和 Factory 的用法和区别 当您处理相同的代码库和不断变化的需求时,在特定时间段内可以更容易地理解/阐明构建器模式。

根据我的经验,通常,您从工厂模式开始,包括几个静态创建者方法,主要隐藏相对复杂的初始化逻辑。 随着您的对象层次结构变得更加复杂(或者添加更多类型、参数),您最终可能会在方法中填充更多参数,更不用说您必须重新编译 Factory 模块。 所有这些东西,增加了创建者方法的复杂性,降低了可读性并使创建模块更加脆弱。

该点可能将是过渡/扩展点。 通过这样做,您可以围绕构造参数创建一个包装器模块,然后您将能够通过添加更多抽象(可能)和实现来表示新的(类似)对象,而无需触及实际的创建逻辑。 所以你的逻辑“不太”复杂。

坦率地说,提到某种“在一步或多步中创建一个对象是有区别的”作为唯一的多样性因素不足以让我区分它们,因为我可以在我遇到的几乎所有情况下使用这两种方法现在没有体验到任何好处。 所以这就是我最后想到的。

I believe, the usage of and the difference between Factory & Builder patterns can be understood/clarified easier in a certain time period as you worked on the same code base and changing requirements.

From my experience, usually, you start with a Factory pattern including couple of static creator methods to primarily hide away relatively complex initialisation logic. As your object hierarchy gets more complex (or as you add more types, parameters), you probably end up having your methods populated with more parameters and not to mention you gonna have to recompile your Factory module. All those stuff, increases the complexity of your creator methods, decreases the readability and makes the creation module more fragile.

This point possibly will be the transition/extension point. By doing so, you create a wrapper module around the construction parameters and then you will be able represent new (similar) objects by adding some more abstractions(perhaps) and implementations without touching actual your creation logic. So you've had "less" complex logic.

Frankly, referring to something sort of "having an object created in one-step or multiple steps is the difference" as the sole diversity factor was not sufficient for me to distinguish them since I could use both ways for almost all cases I faced up to now without experiencing any benefit. So this is what I've finally thought about it.

〃安静 2024-07-24 09:05:35

构建模式强调创建对象的复杂性(通过“步骤”解决)

抽象模式强调(多个但相关的)对象的“抽象”“只是”。

Build pattern emphasizes on complexity of creating object (solved by "steps")

Abstract pattern emphasizes "just" on "abstraction" of (multiple but related) objects.

少年亿悲伤 2024-07-24 09:05:35

两者非常相似,但如果您有大量用于创建对象的参数,其中一些参数是可选的,并且有一些默认值,请选择构建器模式。

Both are very much similar , but if you have a large number of parameters for object creation with some of them optional with some default values , go for Builder pattern.

椒妓 2024-07-24 09:05:35

恕我直言,

Builder 是某种更复杂的工厂。

但是在 Builder 中,您可以使用其他工厂实例化对象,这是构建最终有效对象所必需的。

因此,在谈论“创造模式”的复杂性演化时,你可以这样思考:

Dependency Injection Container -> Service Locator -> Builder -> Factory

IMHO

Builder is some kind of more complex Factory.

But in Builder you can instantiate objects with using another factories, that are required to build final and valid object.

So, talking about "Creational Patterns" evolution by complexity you can think about it in this way:

Dependency Injection Container -> Service Locator -> Builder -> Factory
浅忆 2024-07-24 09:05:35

差异很明显
在构建器模式中,构建器将为您创建特定类型的对象。 你必须告诉什么
建造者必须建造。
在工厂模式中,使用抽象类可以直接构建特定的对象。

在这里,构建器类充当主类和特定类型类之间的中介。
更多抽象。

Difference is clear
In builder pattern, builder will create specific type of object for you. You have to tell what
builder has to build.
In factory pattern , using abstract class you are directly building the specific object.

Here builder class acts as mediator between main class and specific type classes.
More abstraction.

离线来电— 2024-07-24 09:05:35

在我看来
当您想要从一堆其他对象创建一个对象并且部分的创建需要独立于您想要创建的对象时,可以使用构建器模式。 它有助于向客户隐藏零件的创建,使构建者和客户独立。 它用于复杂对象的创建(可能包含复杂属性的对象),

而工厂模式指定您想要创建公共系列的对象并且希望立即创建它。 它用于更简单的对象。

In my opinion
Builder pattern is used when you want to create an object from a bunch of other objects and creation of part needs to be independent of the object you want to create. It helps to hide the creation of part from the client to make builder and client independent. It is used for complex objects creation (objects which may consists of complicated properties)

While factory pattern specifies that you want to create objects of a common family and you want it to be cerated at once. It is used for simpler objects.

向地狱狂奔 2024-07-24 09:05:35

构建器和抽象工厂

Builder 设计模式在某种程度上与抽象工厂模式非常相似。 这就是为什么能够区分使用其中一种或另一种的情况很重要。 对于抽象工厂,客户端使用工厂的方法来创建自己的对象。 在 Builder 的例子中,Builder 类被指示如何创建对象,然后被要求提供该对象,但是将类组合在一起的方式取决于 Builder 类,这个细节造成了两种模式之间的差异。

产品通用界面

实际上,具体构建者创建的产品具有显着不同的结构,因此如果没有理由派生不同的产品,则可以使用公共父类。 这也将构建器模式与抽象工厂模式区分开来,抽象工厂模式创建从公共类型派生的对象。

来自:http://www.oodesign.com/builder-pattern.html

Builder and Abstract Factory

The Builder design pattern is very similar, at some extent, to the Abstract Factory pattern. That's why it is important to be able to make the difference between the situations when one or the other is used. In the case of the Abstract Factory, the client uses the factory's methods to create its own objects. In the Builder's case, the Builder class is instructed on how to create the object and then it is asked for it, but the way that the class is put together is up to the Builder class, this detail making the difference between the two patterns.

Common interface for products

In practice the products created by the concrete builders have a structure significantly different, so if there is not a reason to derive different products a common parent class. This also distinguishes the Builder pattern from the Abstract Factory pattern which creates objects derived from a common type.

From: http://www.oodesign.com/builder-pattern.html

蓝戈者 2024-07-24 09:05:35

许多设计都是从使用工厂方法(不太复杂且通过子类更可定制)开始,然后发展为抽象工厂原型构建器(更灵活,但更复杂)。

Builder专注于逐步构建复杂的对象。

实施:

  1. 明确定义构建所有可用产品表示的通用构建步骤。 否则,您将无法继续实施该模式。
  2. 在基础构建器界面中声明这些步骤。
  3. 为每个产品表示创建一个具体的构建器类并实现其构建步骤。

抽象工厂专门用于创建相关对象系列。 Abstract Factory 立即返回产品,而 Builder 则允许您在获取产品之前运行一些额外的构造步骤。

您可以将抽象工厂Bridge一起使用。 当 Bridge 定义的某些抽象只能与特定实现一起使用时,这种配对非常有用。 在这种情况下,抽象工厂可以封装这些关系并对客户端代码隐藏复杂性。

深入研究设计模式

Many designs start by using Factory Method (less complicated and more customizable via subclasses) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, but more complicated).

Builder focuses on constructing complex objects step by step.

Implementing it:

  1. Clearly define the common construction steps for building all available product representations. Otherwise, you won’t be able to proceed with implementing the pattern.
  2. Declare these steps in the base builder interface.
  3. Create a concrete builder class for each of the product representations and implement their construction steps.

Abstract Factory specializes in creating families of related objects. Abstract Factory returns the product immediately, whereas Builder lets you run some additional construction steps before fetching the product.

You can use Abstract Factory along with Bridge. This pairing is useful when some abstractions defined by Bridge can only work with specific implementations. In this case, Abstract Factory can encapsulate these relations and hide the complexity from the client code.

Dive into design pattern

北座城市 2024-07-24 09:05:35

工厂模式在运行时创建类的具体实现,即它的主要目的是使用多态性来允许子类决定实例化哪个类。 这意味着在编译时我们不知道将创建的确切类,而构建器模式主要关注解决由于类的大量可选字段而出现的伸缩构造函数反模式的问题。 在构建器模式中,没有多态性的概念,因为我们知道在编译时要构造什么对象。

这两种模式的唯一共同主题是将构造函数和对象创建隐藏在工厂方法和构建方法后面,以改进对象构造。

Factory pattern creates a concrete implementation of a class at runtime, i.e its main intention is to use polymorphism to allow subclasses decide which class to instantiate. This means at compile time we dont know the exact class that will be created, while Builder pattern is mainly concerned with solving the problem of telescoping constructors antipattern, which arises due to a large number of optional fields of a class. In builder pattern there is no notion of polymorphism, as we know what object we are trying to construct at compile time.

The only common theme of these two patterns is the hiding of constructors and object creation behind factory methods, and the build method, for improved object construction.

长不大的小祸害 2024-07-24 09:05:35

工厂模式让您一次创建一个对象,而构建器模式让您打破对象的创建过程。 通过这种方式,您可以在创建对象的过程中添加不同的功能。

Factory pattern let you create an object at once at once while builder pattern let you break the creation process of an object. In this way, you can add different functionality during the creation of an object.

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