packagemainimport("fmt""sync")/*go 单例模式实现方式:1. 使用 lock,为了并发安全,使用 lock + double check2. 使用 sync.Once (推荐👍)3. 使用 init()。The init function is only called once per file in a package, so we can be sure that only a single instance will be created参考:- https://blog.cyeam.com/designpattern/2015/08/12/singleton- https://golangbyexample.com/all-design-patterns-golang/- https://medium.com/golang-issue/how-singleton-pattern-works-with-golang-2fdd61cd5a7f*/varlock=&sync.Mutex{}typesinglestruct{}varsingleInstance*singlefuncgetInstance()*single{ifsingleInstance==nil{// 防止每次调用 getInstance 都频繁加锁lock.Lock()deferlock.Unlock()// double check. 如果超过一个goroutine进入这里,保证只有一个 goroutine 创建ifsingleInstance==nil{fmt.Println("Creting Single Instance Now")singleInstance=&single{}}else{fmt.Println("Single Instance already created-1")}}else{fmt.Println("Single Instance already created-2")}returnsingleInstance}funcmain(){fori:=0;i<100;i++{gogetInstance()}// Scanln is similar to Scan, but stops scanning at a newline and// after the final item there must be a newline or EOF.fmt.Scanln()}