首页 > 技术文章 > Go 设计模式--单例模式

flycc 2020-04-03 18:10 原文

Go单例模式

package main

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

type Singleton struct {}

var singleton *Singleton

//只会创建一次
var once sync.Once

func GetInstance() *Singleton{
	once.Do(func(){
		singleton = &Singleton{}
	})
	fmt.Printf("GetInstance =%p\n",singleton) 
	return singleton
}

func main(){
	go GetInstance()
	go GetInstance()
	go GetInstance()
	go GetInstance()
	time.Sleep(time.Second*2)

}

  

推荐阅读