DEV Community

Dsysd Dev
Dsysd Dev

Posted on • Edited on

Writing Better Go Code like a senior engineer with the Singleton Pattern

The singleton pattern is a design pattern that restricts the instantiation of a class to a single object.
Use cases of Singleton pattern

It is a widely-used pattern in software development and is especially useful when dealing with shared resources, such as database connections, configuration settings, or caches.


In this article, we will explore how to implement the singleton pattern in Go.

What is the Singleton Pattern?

The singleton pattern is a creational pattern that ensures that only one instance of a class can be created.

It provides a global point of access to that instance, which is usually created lazily, i.e., when it is first requested.


The singleton pattern is used when a system needs to be limited to a single instance and that instance needs to be accessible throughout the entire application.
Implementing the Singleton Pattern in Go

In Go, the singleton pattern can be implemented using a combination of struct, sync.Once, and a package-level variable.


Here is a basic example of a singleton in Go:

package singleton

import "sync"

type Singleton struct {
    // fields
}

var instance *Singleton
var once sync.Once

func GetInstance() *Singleton {
    once.Do(func() {
        instance = &Singleton{}
    })
    return instance
}
Enter fullscreen mode Exit fullscreen mode

In this example, we define a Singleton struct and a package-level variable named instance of type *Singleton.

We also define a sync.Once variable named once. In the GetInstance() function, we use the once.Do() method to ensure that the instance is created only once.

The once.Do() method takes a function that is executed only once, even if multiple goroutines call the GetInstance() function concurrently.

Advantages of the Singleton Pattern

The singleton pattern offers several advantages:

  1. Single instance: The singleton pattern ensures that only one instance of the class is created and that the instance can be accessed throughout the entire application.
  2. Global access: The singleton pattern provides a global point of access to the instance, making it easy to use throughout the application.
  3. Lazy initialization: The singleton pattern creates the instance lazily, i.e., when it is first requested. This can save memory and resources in applications where the instance is not always needed.

Singleton pattern using init function

Another way to implement the singleton pattern in Go is by using the init function at the package level.

The init function is a special function in Go that gets executed automatically when the package is initialized.

We can leverage this feature to ensure that our singleton instance is created only once when the package is initialized.


Here’s an example implementation of the singleton pattern using the init function:

package singleton

type singleton struct {
    // ...
}

var instance *singleton

func init() {
    // Initialize the singleton instance when the package is initialized
    instance = &singleton{
        // ...
    }
}

func GetInstance() *singleton {
    // Return the singleton instance
    return instance
}
Enter fullscreen mode Exit fullscreen mode

In this implementation, the singleton struct and instance variable are defined at the package level.

The init() function is called when the package is initialized, which is typically when the program starts running.

This function initializes the instance variable with a new singleton struct.

The GetInstance() function simply returns the instance variable, which represents the singleton instance.

This function can be called from anywhere in the program to retrieve the singleton instance.

Using a package level init function for the Singleton pattern ensures that the singleton instance is initialized only once, when the package is initialized, and is then available for use throughout the program.

Conclusion

In this article, we explored the singleton pattern in Go.

We looked at how to implement the pattern using a combination of struct, sync.Once, and package-level variable.

We also discussed the advantages of the singleton pattern and why it is useful in software development.

The singleton pattern is a powerful pattern that can be used in a variety of situations. If you need to limit the number of instances of a class in your Go application, the singleton pattern is a great choice.
Subscribe to my Newsletter

Subscribe

If you like my content, then consider subscribing to my free newsletter, to get exclusive, educational, technical, interesting and career related content directly delivered to your inbox

https://dsysd.beehiiv.com/subscribe

Important Links

Thanks for reading the post, be sure to follow the links below for even more awesome content in the future.

twitter: https://twitter.com/dsysd_dev
youtube: https://www.youtube.com/@dsysd-dev
github: https://github.com/dsysd-dev
medium: https://medium.com/@dsysd-dev
email: dsysd.mail@gmail.com
linkedin: https://www.linkedin.com/in/dsysd-dev/
newsletter: https://dsysd.beehiiv.com/subscribe
gumroad: https://dsysd.gumroad.com/

Top comments (0)