Golang 實現單例模式


只適用於單線程環境

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")
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM