Singleton design pattern in go

Yashod Perera
2 min readJul 26, 2021
Photo by Kelly Sikkema on Unsplash

Singleton design pattern is the one of easiest design pattern and it is a creational design pattern. Let's go through what is singleton, where should we user it, how to implement it and implementation in goLang.

What is singleton design pattern

It says single. Yes singleton design pattern use only single object throughout the application. It saves memory and help garbage collector by not giving many objects to clean.

Then What If I initiate an object with the Class? Basically it gives the same object and it does not create a new one.

Where should we use it

  • Where we need only one instance of the class. Ex — Database instance, Log instance.
  • When we need to access the single object throughout the application.

How we should implement this

We create a method to create the object. This method make sure to pass the existing object that if there is any created object. Pointers are used to pass the same object in go.

Implementation in goLang

First we can implement this using simple structure as follows.

But above code is not thread safe in go lang. We need to use sync to ensure the thread safety when implementing singleton pattern.

Hope this will be helpful.

If you have found this helpful please hit that 👏 and share it on social media :).

--

--

Yashod Perera

Technical Writer | Tech Enthusiast | Open source contributor