Home >Backend Development >Golang >How to Implement the Singleton Design Pattern in Go?

How to Implement the Singleton Design Pattern in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-13 01:34:02190browse

How to Implement the Singleton Design Pattern in Go?

Implementing the Singleton Design Pattern in Go

The Singleton design pattern restricts the instantiation of a class to a single object. While its use is often debated, in certain scenarios, it can be a practical solution.

Implementation

To implement the Singleton pattern in Go, we start with the following code:

package singleton

type single struct {
        O interface{};
}

var instantiated *single = nil

func New() *single {
        if instantiated == nil {
                instantiated = new(single);
        }
        return instantiated;
}

Here, a private struct single defines the object we want to limit to a single instance. The private variable instantiated keeps track of the object's instantiation. We define a public function New() to retrieve the instance.

Thread Safety

However, this implementation is not thread-safe. To address this, we can use the sync.Once type:

package singleton

import "sync"

type single struct {
        O interface{};
}

var instantiated *single
var once sync.Once

func New() *single {
        once.Do(func() {
                instantiated = &single{}
        })
        return instantiated
}

Here, sync.Once ensures that the singleton is only instantiated once, even in concurrent environments.

Alternatives

Alternatively, it's worth considering package-level scoping as a simple way to enforce singleton behavior.

In summary, implementing the Singleton pattern in Go involves controlling instance creation through a single function. Thread safety can be achieved using sync.Once. However, as suggested, it's wise to question the need for singletons in your code to ensure a well-structured and maintainable design.

The above is the detailed content of How to Implement the Singleton Design Pattern in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn