What is the difference between Builder Design pattern and Factory Design pattern? [closed]
Asked Answered
R

27

829

What is the difference between the Builder design pattern and the Factory design pattern?

Which one is more advantageous and why ?

How do I represent my findings as a graph if I want to test and compare/contrast these patterns ?

Revocation answered 16/4, 2009 at 19:39 Comment(4)
Since they do different things, what do you mean by "advantageous"?Goldsberry
Builder is a more complex version of constructor - while factory method is a simplified one.Jempty
@DávidHorváth I wouldn't describe a Builder as "more complex". When you're dealing with a constructor that has 100 parameters, and you only care about 3 of those, and you know the number of parameters might change in the future, using the Builder pattern would make everyone's life a lot simpler.Marcum
@Marcum Complicated usage and architectural complexity are two different things. I focused on the latter.Jempty
N
571

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

Nautch answered 16/4, 2009 at 19:46 Comment(6)
This is exactly the difference. The Builder is only needed when an object cannot be produced in one step. One great an example of this would be in the de-serialization process for a complex object. Often times the parameters for the complex object must be retrieved one by one.Sixfold
For the first sentence, I would say there absolutely is often a more advantageous solution that applies broadly... we just don't see these, because they end up baked directly into programming languages.Cotsen
@Joel: I agree that some patterns are more common that others (for instance, Factory seems to be more common than Builder), but what I meant is that none of them is always better than the other, no matter what the scenario looks like.Nautch
@AdrianGrigore what if mix both of them??aso.net mvc have ControllerBuilder that have set and get method for ControllerFactory classCatabasis
Goood answer, although 2 things which is worth adding is: 1) Builder is mainly used to build POJOs using Fluent API (e.g. Person.builder().withName("Sam").withAge(38).build(). 2) In my experiene, builder is useful for POJO creation for domain objects, whereas factory is useful for creating a service objects like PdfGeneratorFactory class. The service object could be cached within factory for more than 1 time use, whereas builder always creates a new object by design.Caddie
All this answer does is repeat Wiki. It adds nothing more. Needs own words to explain what the differences are.Joaniejoann
T
515

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

Treytri answered 22/1, 2012 at 5:15 Comment(4)
Thats not the correct usage of builder pattern imo, even in the wiki link you pased usage is different. This FruitBuilder is some mix of Director and Builder component where you invoke build() which should belong to Director and setters which belong to Builder component. Director should contain business logic on how to create object using Builders methods. Fluent apis are not builder patterns and StringBuilder is also not builder pattern.Perfumer
There are two different patterns that are commonly called "builder": a) builder according to "Design Patterns: Elements of Reusable Object-Oriented Software" by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides --- b) builder according to "Effective Java", by Joshua Bloch. "Consider a builder when faced with many constructor parameters." This pattern uses method cascading / fluent interface to initialize (immutable) objects with a lot of attributes.Unctuous
The Builder build() method should return new Fruit(name, color, firmness) like the factory example instead of returning new Fruit(this). Or am I missing something? @Talavera316Boss
@Boss Yes, definitely.Voroshilovgrad
A
311

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.

Anguiano answered 16/4, 2009 at 19:44 Comment(1)
The builder pattern is like zooming in to the construction of the big object. The big object is composed of other object which is composed further on like recursion. While factory will just get you the thing in one call. Is this understanding correct?Consonantal
C
70

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.

Cotsen answered 16/4, 2009 at 19:44 Comment(1)
Just some hint: good example for builder pattern is "fluent interface" and ADO.NET is full with "factory" and "abstract factory" implementations (ie. DbFactory).Cartography
C
61
  • 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

Cinchonidine answered 18/6, 2013 at 6:15 Comment(0)
C
38
Builder Factory
Return only single instance to handle complex object construction Return various instances on multiple constructors
No interface required Interface 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

Couplet answered 6/2, 2018 at 0:45 Comment(0)
G
25

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

Gamy answered 9/10, 2017 at 6:43 Comment(1)
Thanks for providing the sample code! Your examples differentiate these 2 patterns very well.Luettaluevano
E
20

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.
Evade answered 17/4, 2009 at 10:0 Comment(0)
S
15

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.

Silurid answered 15/1, 2017 at 17:15 Comment(7)
nice answer, elaborate explain.Briseno
can you please explain meaning of "Separate the construction of a complex object from its representation "Cortisol
@Cortisol the explanation is to long for a comment, that‘s why i wrote another answer.Silurid
@Silurid Where is that answer or source from where i can read ?Cortisol
@Cortisol i recommend you to read the book „Design Patterns“ - amazon.de/Patterns-Elements-Reusable-Object-Oriented-Software/…Silurid
@Silurid yes will read that, you seem to have knowledge of OOP as well, where did you study that and Head first OOPs ?Cortisol
@Cortisol Most of this i studied by myself during programming. If you want to learn about oop and ood you need to check out Robert C. Martin (uncle Bob), the „solid“-principles, the metrics „cohesion & coupling“ and in the end tdd. But experience is one of the most Important things.Silurid
G
7

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.

Gunthar answered 24/12, 2018 at 3:50 Comment(0)
C
6

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.

Consonantal answered 22/8, 2014 at 8:49 Comment(3)
Surely it is better to have no car at all than an invalid car - what if you only find the problem when you come to use the breaks?Maegan
@Maegan : I am not insisting that its a good design from prospective of commercial project etc rather, the intention of quotinng this example to exemplify the difference between the patterns. Definately, you are correct that this is bad from user experiance that getting bad car but, consider, there is plant in which cars are made & some part is malfunctioning then the car does get produced but with a bad break which would be found out at the time of testing & shipping of that car to customer is stopped.Consonantal
I would like to clarify that I am actually a big fan of the builder pattern, However, not for the reason you have given. An object that is invalid should fail on construction, the further down the process a bug is found the more expensive it is. With the builder pattern it would be normal for the build method (in your example called getCar()) to throw an exception if there is any required data missing.Maegan
D
6

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

Delightful answered 15/2, 2016 at 19:35 Comment(0)
B
5

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.

Baron answered 21/1, 2020 at 11:12 Comment(0)
W
4

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.
Whorish answered 6/1, 2016 at 1:37 Comment(1)
can you please explain meaning of " decouples the representation from the process of constructing the complex object "Cortisol
S
3

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.

Silurid answered 4/3, 2018 at 9:6 Comment(1)
This explains the " separation of construction of complex object from its representation"Cortisol
R
3

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();
}
Redundancy answered 17/8, 2019 at 10:49 Comment(0)
L
2

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.

Lavone answered 15/9, 2016 at 23:41 Comment(0)
C
2

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.

Cunning answered 15/12, 2016 at 13:33 Comment(0)
V
1

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

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

Valvular answered 10/6, 2013 at 21:1 Comment(0)
S
1

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.

Saltire answered 30/9, 2015 at 10:3 Comment(0)
H
1

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
Holtz answered 5/11, 2017 at 13:29 Comment(0)
L
0

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

Latifundium answered 15/1, 2013 at 22:49 Comment(0)
H
0

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.

Hammer answered 2/9, 2013 at 5:7 Comment(0)
S
0

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.

Syrinx answered 6/2, 2014 at 6:59 Comment(0)
E
0

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

Enthetic answered 19/8, 2020 at 16:47 Comment(0)
S
-2

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.

Systematism answered 19/2, 2016 at 6:28 Comment(0)
M
-2

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.

Moorland answered 1/8, 2016 at 10:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.