739
votes

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 ?

27
Since they do different things, what do you mean by "advantageous"?S.Lott
Builder is a more complex version of constructor - while factory method is a simplified one.Dávid Horváth
@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.Aberrant
@Aberrant Complicated usage and architectural complexity are two different things. I focused on the latter.Dávid Horváth

27 Answers

520
votes

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

421
votes

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

298
votes

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.

68
votes

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.

54
votes
  • 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

23
votes

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

20
votes

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.
13
votes

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.

9
votes
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

7
votes

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.

7
votes

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.

5
votes

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
  3. Replacement to Factory method/Abstract Factory in this scenario : Too Many arguments to pass from client program to the Factory class that can be error prone
  4. Some of the parameters might be optional unlike in Factory which forces to send all parameters

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
  4. You can substitute new Concrete Objects for interface and client (caller) should not be aware of all concrete implementations
  5. Client always access interface only and you can hide object creation details in Factory method.

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)

Have a look at related posts:

Keeping builder in separate class (fluent interface)

Design Patterns: Factory vs Factory method vs Abstract Factory

You can refer to below articles for more details:

sourcemaking

journaldev

4
votes

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.
3
votes

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.

3
votes

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.

2
votes

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.

2
votes

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();
}
2
votes

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.

1
votes

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

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

1
votes

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.

1
votes

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
0
votes

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.

0
votes

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.

0
votes

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

0
votes

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

-2
votes

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.

-2
votes

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.