Skip to main content

Command Palette

Search for a command to run...

Golang - Singleton Pattern

Updated
3 min read
Golang - Singleton Pattern
M

Senior Freelancer & Technical Lead

Working as a Golang developer since 2020. Working as a mobile developer since 2013.

Focussed on architecture, testability and clean code. Open minded & product driven. Based in Rhede, available world-wide

In software engineering, the Singleton pattern is a software design pattern that restricts the instantiation of a type to one object. This is useful when exactly one object is needed to coordinate actions across the system. In this article, we will discuss how to implement the Singleton pattern in Golang with an example code.

Singleton Pattern in Golang

The Singleton pattern is implemented in Golang using a struct type and a private package-level variable that holds the only instance of the struct. The struct's constructor function is exported and is used to return the instance of the struct. Here is an example implementation of the Singleton pattern in Golang:

package singleton

type Singleton struct {
    name string
}

var instance *Singleton

func GetInstance() *Singleton {
    if instance == nil {
        instance = &Singleton{name: "Golang Singleton"}
    }
    return instance
}

func (s *Singleton) GetName() string {
    return s.name
}

In the above implementation, we have defined a struct type Singleton with a single field name. We have also declared a private package-level variable named instance of type *Singleton. The GetInstance() function returns the instance of the Singleton struct. If the instance is nil, it creates a new instance of the Singleton struct and assigns it to the instance variable.

Finally, we have a method GetName() that returns the name of the Singleton struct.

Example Usage

Let's see how we can use the Singleton struct in our code.

In the above code, we have imported the Singleton package and created two instances s1 and s2 of the Singleton struct using the GetInstance() function. We then printed the name of both instances using the GetName() method. Finally, we checked if s1 and s2 are the same instances using the == operator.

package main

import "singleton"

func main() {
    s1 := singleton.GetInstance()
    s2 := singleton.GetInstance()

    println("s1.GetName()", s1.GetName())
    println("s2.GetName()", s2.GetName())

    println("s1 == s2", s1 == s2)
}

Thread-safe singleton

To create a thread-safe variant of the Singleton pattern in Golang, we can use the sync.Once package. We modify the instance variable to be of type sync.Once, and then use its Do() method to create a new instance of the Singleton struct only once. Here is an example implementation:

package singleton

import "sync"

type Singleton struct {
    name string
}

var (
    instance *Singleton
    once     sync.Once
)

func GetInstance() *Singleton {
    once.Do(func() {
        instance = &Singleton{name: "Safe Golang Singleton"}
    })
    return instance
}

func (s *Singleton) GetName() string {
    return s.name
}

In this implementation, we have declared a sync.Once variable named once. The GetInstance() function uses the once variable's Do() method to create a new instance of the Singleton struct only once. The GetName() method remains the same as before.

With this implementation, we ensure that only one instance of the Singleton struct is created, and that the creation is thread-safe.

You can use this implementation in the same way as before.

Conclusion

The Singleton pattern is a useful design pattern that restricts the instantiation of a type to one object. In this article, we have discussed how to implement the Singleton pattern in Golang with an example code. I hope this article helps you understand the Singleton pattern in Golang. Happy coding!

M

Hi and thanks to share this blog post. I have two questions: 1) In this example, you use private variable, why you don't expose it? in other word what difference between exposed and unexposed variable in this pattern? In my opinion when we expose it, other pkg can use it with nil value and as a result the application panics. is that the reason we use unexposed variable?

2) what happening if we don't expose type Singleton? In this example Singleton type is exposed, other pkg can create instance from Singleton type directly and as a result we have many instance from Singleton type.

thanks Matthias

1
M

Well the idea of a singleton is, that there is only one instance in the whole app (at least when you look at languages that support the keyword static). You do not need to set the singleton private - but then somebody has to take care of the initiation, which is totally find and usually done in DI frameworks or in main() when you provide your own dependencies.

The reason why I made the singleton private can be seen in the "thread-safe" example. The file takes control over thread handling in this example. Another way, if you want to let somebody else take control over how it is done, is that you need to make sure, that the singleton is initiated before anyone can access it.

I hope that answered your questions.

1

Golang Patterns

Part 19 of 19

Welcome to the Golang Patterns tutorial series! In this series, we will explore the various software patterns that can be applied in Golang to create flexible, scalable, and maintainable software.

Start from the beginning

Golang Design Patterns - Overview

A curated list of design pattern articles for Golang

More from this blog

Matthias Bruns

69 posts