Skip to main content

单例

懒汉模式

package main

import (
"fmt"
"sync"
)

type Singleton struct {
data string
}

var instance *Singleton
var once sync.Once

func getInstance() *Singleton {
once.Do(func() {
instance = &Singleton{"Lazy Initialization"}
})
return instance
}

func main() {
instance1 := getInstance()
fmt.Println(instance1.data)

instance2 := getInstance()
fmt.Println(instance2.data)
}


恶汉模式

package main

import "fmt"

type Singleton struct {
data string
}

var instance *Singleton = &Singleton{"Eager Initialization"}

func getInstance() *Singleton {
return instance
}

func main() {
instance1 := getInstance()
fmt.Println(instance1.data)

instance2 := getInstance()
fmt.Println(instance2.data)
}