~/Factory Pattern in Go Explained

Nov 15, 2019


The factory pattern is used in Go to encapsulate object creation, returning objects through a function instead of exposing the details directly.

Define an interface and concrete types. Then, use a factory function to return the interface.

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
type Animal interface {
    Speak() string
}

type Dog struct{}
func (d Dog) Speak() string { return "Woof" }

type Cat struct{}
func (c Cat) Speak() string { return "Meow" }

func AnimalFactory(animalType string) Animal {
    if animalType == "dog" {
        return Dog{}
    }
    if animalType == "cat" {
        return Cat{}
    }
    return nil
}

Create objects like this:

1
2
a := AnimalFactory("dog")
fmt.Println(a.Speak()) // Woof

This hides object details and simplifies instantiation. Useful when the creation process is complex or should be centralized.

For a deep dive, see golang design patterns and the official Go wiki.

Tags: [go] [factory] [patterns]