Skip to content

Design Patterns: Factory

Posted on:September 18, 2024 at 08:27 PM

Table of Contents

Open Table of Contents

Introduction

In this article we’ll explore the Factory pattern in Go, this pattern allows us to create an instance of an object with sensible default values. A common example of this patter in Go would be the New method we use to create “instances” of a struct.

How do we implement it?

So, let’s suppose you’re developing an e-commerce website, and you have a struct called Product, let’s see how you can use the factory pattern to create new instances of it.

package main

import (
	"fmt"
	"time"
)

// Product represents a product to buy in your app.
type Product struct {
	Name        string
	Description string
	Price       int
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

// New creates new instances of the Product type.
func (p *Product) New() *Product {
	// We create the Product with some default values.
	product := Product{
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}
	return &product
}

func main() {
	factory := Product{}
	product := factory.New()

	fmt.Println("My product was created at:", product.CreatedAt.UTC())
}

Execute the code in this playground

And that’s it! this pattern is easy to use and implement in Go.