DEV Community

Bruno Souza
Bruno Souza

Posted on

Golang - Singleton Design pattern

Conceitualmente o padrão singleton define que somente uma instância deve existir em todo o sistema.
É como ter um guardião solitário que garante que apenas uma única cópia de si mesma esteja presente, independentemente de quantas vezes seja chamado.

Estou avançando nos estudos em golang e decidi mergulhar na implementação deste padrão tão debatido e controverso.
É aquele tipo de padrão que desperta paixões e críticas, amado por alguns como uma solução elegante e odiado por outros como um antipadrão a ser evitado a todo custo.

singleton.go

package main

import (
    "fmt"
    "sync"
)

var lock = &sync.Mutex{}

type singleton struct {
}

var singleInstance *singleton

func getInstance() *singleton {
    if singleInstance == nil {
        lock.Lock()
        defer lock.Unlock()
        if singleInstance == nil {
            fmt.Println("create singleton")
            singleInstance = &singleton{}
        } else {
            fmt.Println("singleton already created.")
        }
    } else {
        fmt.Println("singleton already created.")
    }

    return singleInstance
}
Enter fullscreen mode Exit fullscreen mode

main.go

package main

import (
    "fmt"
)
func main() {
    for i := 0; i < 3; i++ {
        go getInstance()
    }
    fmt.Scanln()
}
Enter fullscreen mode Exit fullscreen mode

Saída esperada

create singleton
singleton already created.
singleton already created.
Enter fullscreen mode Exit fullscreen mode

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs