Go 设计模式--单例模式

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)

}

  

posted @ 2020-04-03 18:10  醉深梦始  阅读(191)  评论(0)    收藏  举报