Creating a Google Cloud Pub/Sub client using the Singleton design pattern in Golang

Singleton Design Pattern is a creational design pattern used when only a single instance of a class or struct should exist. The lone instance is called the singleton object.

To demonstrate the design pattern in Golang, let's take the example of a pub/sub client where only one instance of the client should be created and it should be used throughout the application. Below is the code to create the pub/sub client.

package analytics

Note the following:

  1. There is a check at the very beginning for nil instance. This is to prevent the expensive lock operations every time the createPubSubClient() method is called. If this check fails then it means that instance is already initialized.
  2. The instance is initialized inside the lock.
  3. There is another check for nil instance after the lock is acquired. This is important because, by the time a lock is obtained for the resource, it might have already been initialized by another process or goroutine. This check prevents each process or goroutine from creating its own pub/sub client.

A cleaner alternative to achieve the same is to use sync.Once which performs an operation only once as follows:

package analytics

Software Engineer at AirAsia

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store