Member-only story
Singleton Pattern You Should Know in Golang(Design Patterns 03)
Singleton Pattern in Go: Eager, Lazy, or Double-Checked?
Contact Author@:Medium,LinkedIn,Twitter

Hello, here is Wesley, Today’s article is about singleton pattern in Go. Without further ado, let’s get started.💪
Singleton Pattern, perhaps the most well-known design pattern among all. It’s also a type of creational pattern. When a struct only allows one instance to exist, we’ll use this design pattern. The unique instance of this struct is called the singleton object. It ensures that a class has only one instance and provides a global access point.
In Go language, the implementation of the singleton pattern is relatively simple, mainly achieved through the use of sync.Once
and a global variable to ensure thread safety.
What is Singleton Pattern
The core idea of the Singleton Pattern is:
- Uniqueness: There exists only one instance throughout the entire application.
- Global Access: Provides a global access point to obtain this instance.
Applicable Scenarios
- Need to control resource access, such as database connections, thread pools, etc.