Builder vs Factory Method Pattern: An In-Depth Comparison


One of the most fundamental things you can do in the code is to create new objects.

Whether you create a new instance manually or use a dependency injection container, classes need other objects to function properly.

But what happens when object creation is not straightforward?

Well, then you can use creational design patterns.

And Factory Method and Builder are probably the two most used patterns for creating new objects. So, what’s the difference Builder vs Factory Method?

The Builder and the Factory Method are both creational design patterns. However, you can use the Builder pattern when you want to create a complex object in a step-by-step manner. On the other hand, use the Factory Method to create objects without specifying the exact type of object that will be created.

If you just want a quick comparison, take a look at the following table.

Builder patternFactory Method pattern
Creates complex objects in a step-by-step fashionDefines a method for creating an object but allows subclasses to determine which object should be created
Uses a builder class to create an objectUses a concrete factory class that contains method for instancing a desired object
Highly flexibleNot too much flexibility

However, this article takes a closer look at these patterns and compares their key features and differences to help you understand when to use each one.

Whether you’re a seasoned software developer or just starting out, you should find will provide valuable insights into these important design patterns.

Also, I don’t want to brag too much, but a bigger comparison table is waiting for you if you keep reading.

What is the Builder pattern?

builder pattern

The Builder design pattern is a creational design pattern that allows you to create complex objects in a step-by-step manner using a builder object. The idea behind the Builder pattern is to separate the construction of an object from its representation so that the same construction process can create different representations.

This pattern is useful when you need to create an object that has a lot of constructor parameters. It is also useful if the parameters are unknown beforehand. With the Builder pattern, you have greater flexibility and control over the construction process.

You might use the Builder pattern when:

  • You want to give your users different options for configuring an object, but you don’t want them to have to worry about the details of how the object is built.
  • You want to enforce invariants on an object under construction, such as ensuring that all required fields are set before the object is used.
  • You want to be able to reuse components from other objects when building new objects.

When deciding whether to use the Builder pattern, ask yourself whether you need to give your users different options for configuring an object and whether the construction process is complicated enough to be separated into smaller and simpler steps.

I have a whole separate article about the Builder pattern, which you can read here. Here is the simple structural C# code from that article.

Notice the IBuilder interface and Builder class. It is used to instantiate a Product and initialize its parts.

class Director
{
    private IBuilder _builder;

    public Director(IBuilder builder)
    {
        _builder = builder;

        _builder.BuildPart1();
        _builder.BuildPart2();
        Product finishedProduct = _builder.Build();
    }
}

interface IBuilder
{
    void BuildPart1();
    void BuildPart2();
    Product Build();
}

class ConcreteBuilder : IBuilder
{
    private Product _product;

    public ConcreteBuilder()
    {
        _product = new Product();
    }

    public void BuildPart1()
    {
        _product.Part1 = "part1";
    }

    public void BuildPart2()
    {
        _product.Part2 = "part2";
    }

    public Product Build()
    {
        return _product;
    }
}

public class Product
{
    public string Part1 { get; set; }
    public string Part2 { get; set; }
}

What is the Factory Method pattern?

factory method pattern

The Factory Method pattern is a pattern responsible for creating objects without specifying the exact class of object that will be created. It is implemented by creating an interface or an abstract class with a factory method responsible for creating objects. Then, subclasses override the factory method to specify what type of object should be created.

The advantage of this pattern is that you can use it to create new objects without changing the base interface. This can be useful when the type of object to be created is not known or when the decision about what object to create needs to be made at runtime.

One disadvantage of the Factory Method pattern is that it can lead to additional code. For example, if you have a lot of different types of products that need to be created, you’ll end up with many different factory methods. But, the additional code is justified since you get a loose coupling of the creation logic.

The following code sample shows the C# structural code.

//interface for creating the objects
interface IProduct
{
}

//Concrete Product 1, whose object is created
class ConcreteProduct1 : IProduct
{
}

//Concrete Product 2, whose object is created
class ConcreteProduct2 : IProduct
{
}

//The Creator has a Factory Method.
//This class is actually responsible for creating objects.
abstract class Creator
{
    public abstract IProduct FactoryMethod(int product_number);
}

//Concrete Creator will create the objects
//according to the product number passed to the Factory Method.
class ConcreteCreator : Creator
{
    public override IProduct FactoryMethod(int product_number)
    {
        switch (product_number)
        {
            case 1:
                return new ConcreteProduct1();
            case 2:
                return new ConcreteProduct2();
            default:
                Console.Write("Invalid Product number");
                return null;
        }
    }
}

One thing worth mentioning is that the Factory Method pattern will only return one object. If you need to create families of related or dependent objects in one go, take a look at the Abstract Factory pattern.

Here is a simple structural C# code for the Factory Method pattern. I go into much more detail in a separate article about the Factory Method pattern.

Factory Method vs Builder patterns: what are the differences?

Before we discuss the differences, let’s address what they have in common.

Builder and Factory Method are both creational design patterns, meaning that they both add a layer of abstraction between creation and the client code. This means that the client code can remain clean and simple while the construction of the complex object can be delegated to another class.

This separation of concerns is a key benefit of both patterns.

Also, both patterns allow for the construction of objects that are not known at compile-time. This is important in situations where the type or structure of the object to be created may not be known until runtime.

Ok, those were the similarities.

Now, let’s see the differences and comparisons by the following points:

  1. Purpose – The primary purpose of the Builder pattern is to provide a flexible and customizable way to create complex objects. On the other hand, use the Factory Method pattern to create objects without specifying the exact class of object that will be created.
  2. The problem it solves – If you have a class with many constructors, and every constructor has a high number of parameters, also known as the Telescoping Constructor Pattern, you can use Builder to create an object more easily. Factory Method allows you to pick which object to create at runtime.
  3. Implementation – The Builder typically involves the creation of a separate builder class, which is responsible for constructing the object. The Factory Method, on the other hand, involves the creation of a factory class, which contains a method that creates the object.
  4. Flexibility – The builder class is highly flexible. It has methods that you can mix and match to initialize the desired object. When you are done, use the Build method to get the desired object. If you need to have a more rigid initialization process, use the Progressive Builder implementation. Factory class contains a method that returns a concrete instance based on some input parameter. Usually, you will recognize those methods by having switch statements inside them.
  5. Complexity – Both patterns are not complex to implement.
  6. Popularity – Since they are not too complex, they are very popular and are commonly used in many different types of applications.

The following table illustrates the comparison between these two creational patterns.

ComparisonBuilder patternFactory Method pattern
TypeCreationalCreational
PurposeCreates complex objects in a step-by-step fashionDefines a method for creating an object but allows subclasses to determine which object should be created
Problems it solvesComplex constructing processPicking which object to create at runtime
ImplementationUses a builder class to create an objectUses a concrete factory class that contains method for instancing a desired object
FlexibilityHighly flexibleNot too much flexibility
ComplexityLowLow
PopularityHighHigh

Can you use Factory Method and Builder together?

The Factory Method and Builder patterns can be combined to create an object. First, the Factory Method selects which object to create. Then the Builder pattern adds the details. This separation of concerns allows for more flexibility and the ability to add new features in the future easily.

For example, imagine you are building a system for managing documents in an office. The requirement is to have different documents, such as text documents, spreadsheet documents, etc.

In that case, you could use the Factory method pattern to create different types of documents and use the Builder pattern to populate the content of each document. For example, the text for a text document, the data for a spreadsheet document, etc.

Overall, using these two patterns together can be a powerful way to create complex objects in a modular and flexible way.

Conclusion

In summary, Factory and Builder are very popular and widely used in all sorts of applications. However, since they have some differences, it’s essential to know when to use which pattern.

This article has answered your questions on the difference between the Builder and Factory Method. Armed with this knowledge, you should know when to apply them in your code.

Recent Posts