Builder Pattern in Go

Written by Henk Bourgonje on 6/20/2022

The Builder pattern is a design pattern used in software development to separate the construction of a complex object from its representation. It provides a flexible and expressive API for building complex objects, making it a popular choice among Golang developers.

In Golang, the Builder pattern is typically implemented using a separate struct for the builder. This struct has methods for setting the various properties of the object being built, such as size, color, or other attributes. This approach allows for a more flexible and expressive API, as well as improved performance by reducing the amount of memory and CPU resources required to create and configure objects.

Let's take a look at a code sample to better understand how the Builder pattern works in Golang. In this example, we'll create a struct for a car, and a separate struct for the car builder. The car builder struct will have methods for setting the various properties of the car object.

type Car struct {
    Make  string
    Model string
    Year  int
    Color string
}

type CarBuilder struct {
    car *Car
}

func (b *CarBuilder) Make(make string) *CarBuilder {
    b.car.Make = make
    return b
}

func (b *CarBuilder) Model(model string) *CarBuilder {
    b.car.Model = model
    return b
}

func (b *CarBuilder) Year(year int) *CarBuilder {
    b.car.Year = year
    return b
}

func (b *CarBuilder) Color(color string) *CarBuilder {
    b.car.Color = color
    return b
}

func (b *CarBuilder) Build() *Car {
    return b.car
}

func NewCarBuilder() *CarBuilder {
    return &CarBuilder{car: &Car{}}
}

In this code sample, we have a struct Car that represents a car object. The CarBuilder struct has methods for setting the make, model, year, and color of the car. These methods return a pointer to the CarBuilder struct, allowing for method chaining.

The Build() method of the CarBuilder struct returns a pointer to the Car struct that was created and configured using the builder. Finally, the NewCarBuilder() function returns a new instance of the CarBuilder struct.

To use the builder, we would create a new instance of the CarBuilder struct and use its methods to set the properties of the car object:

carBuilder := NewCarBuilder()
car := carBuilder.Make("Toyota").Model("Camry").Year(2020).Color("red").Build()

This will create a new car object with the specified make, model, year, and color.

In conclusion, the Builder pattern is a useful design pattern for Golang developers who need to create flexible and expressive APIs for building complex objects. By separating the construction of complex objects from their representation, the Builder pattern allows for a more efficient and maintainable codebase.