How to Implement the Singleton Design Pattern in Go?

Mary-Kate Olsen
Release: 2024-11-13 01:34:02
Original
174 people have browsed it

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;
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template