目录

只适用于单线程环境

package main

import "fmt"

type Single struct {

}

var single *Single

func GetSingle() *Single {
	if single == nil {
		single = &Single{}
	}
	return single
}

func main() {
	fmt.Printf("%p\n", GetSingle())
	fmt.Printf("%p\n", GetSingle())
	fmt.Printf("%p\n", GetSingle())
}

支持并发版本

package main

import (
	"fmt"
	"sync"
	"time"
)

type Single2 struct {

}

var single2 *Single2
var lock *sync.Mutex = &sync.Mutex{}

func GetSingle2() *Single2 {
	lock.Lock()
	defer lock.Unlock()
	if single2 == nil {
		single2 = &Single2{}
	}
	return single2
}

func main() {
	go fmt.Printf("%p\n", GetSingle2())
	go fmt.Printf("%p\n", GetSingle2())
	go fmt.Printf("%p\n", GetSingle2())
	time.Sleep(time.Second)
	fmt.Println("done")
}

优化并发版本

package main

import (
	"fmt"
	"sync"
	"time"
)

type Single2 struct {

}

var single2 *Single2
var lock *sync.Mutex = &sync.Mutex{}

func GetSingle2() *Single2 {
	if single2 == nil {
		lock.Lock()
		defer lock.Unlock()
		if single2 == nil {
			single2 = &Single2{}
		}
	}
	return single2
}

func main() {
	go fmt.Printf("%p\n", GetSingle2())
	go fmt.Printf("%p\n", GetSingle2())
	go fmt.Printf("%p\n", GetSingle2())
	time.Sleep(time.Second)
	fmt.Println("done")
}

sync.Once版本

package main

import (
	"fmt"
	"sync"
	"time"
)

type Single3 struct {

}

var once sync.Once
var single3 *Single3

func GetSingle3() *Single3 {
	once.Do(func() {
		single3 = &Single3{}
	})
	return single3
}

func main() {
	go fmt.Printf("%p\n", GetSingle3())
	go fmt.Printf("%p\n", GetSingle3())
	go fmt.Printf("%p\n", GetSingle3())
	time.Sleep(time.Second)
	fmt.Println("done")
}