Builder is a common pattern to create or initialize a particular object. It helps to break down individual steps of the creation by providing functions we can use to set different properties and then usually with a Build method, which uses these properties to create the object.

Implementing Builder pattern

  1. Define a struct with all the properties of the object.
package builder

type User struct {
    UID      string
    Name     string
    Email    string
    Password string
}
  1. Create methods to set the properties of the object.
// creates a new UID for the user
func (u *User) createUid() *User {
    u.UID = generateUID()
    return u
}

// sets the name and email of the user
func (u *User) setNameEmail(name, email string) *User {
    u.Name = name
    u.Email = email
    return u
}

// sets the password of the user
func (u *User) setPassword(password string) *User {
    u.Password = hashPassword(password)
    return u
}
  1. Create a Build method to create the object.
// Build creates a new user
func (u *User) Build() *User {
    return u
}

Example usage

package main

import (
    "builder-pattern/builder"
    "fmt"
)

func main() {
    user := &builder.User{}
    user.createUid().setNameEmail("Adharsh", "dev@adharsh.in").setPassword("password").Build()

    fmt.Println(user)
}

The key is to make the methods return the pointer to the object so that we can chain the methods together. This is a common pattern in Go and is used in many places.