Creational

Singleton

Ensures a class has only one instance and provides global access to it.

Configuration managementLoggingDatabase connections

Understanding Singleton

The Singleton pattern ensures a class has only one instance and provides a global point of access to it. In Go, we use sync.Once to guarantee thread-safe initialization, making it perfect for shared resources like database connections, configuration managers, or logging systems.

How It Works

A
Client A
B
Client B
Singleton
GetInstance()
instance
0x1234abcd
sync.Once
GetInstance()
GetInstance()
*instance
1

First Request

Client A requests the singleton instance. Since no instance exists, one is created.

1 / 5

Basic Implementation

The simplest thread-safe singleton in Go uses sync.Once:

main.go
Loading editor...

Real-World Example: Database Connection

A common use case is managing database connections. Even with 100 concurrent goroutines, the connection is created only once:

main.go
Loading editor...