Singleton design pattern in go

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.

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 we need only one instance of the class. Ex — Database instance, Log instance.
  • When we need to access the single object throughout the application.

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.

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 :).

Technical Writer | Tech Enthusiast | Open source contributor