How is the singleton pattern implemented in Golang?

In Go language, you can achieve the singleton pattern by using the following method:

  1. Singleton pattern implemented using sync.Once.
package singleton

import "sync"

type singleton struct{}

var instance *singleton
var once sync.Once

func GetInstance() *singleton {
    once.Do(func() {
        instance = &singleton{}
    })
    return instance
}

In this example, the functionality of only executing once is achieved through sync.Once, ensuring that the instance is created only once.

  1. Singleton pattern implemented using sync.Mutex.
package singleton

import "sync"

type singleton struct{}

var instance *singleton
var mu sync.Mutex

func GetInstance() *singleton {
    mu.Lock()
    defer mu.Unlock()

    if instance == nil {
        instance = &singleton{}
    }
    return instance
}

In this example, mutual exclusion is achieved through the use of sync.Mutex, ensuring that the creation and retrieval of instances is thread-safe.

The choice between these two methods for implementing singleton pattern depends on specific needs and preferences.

bannerAds