• 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
    ", GetSingle())
    	fmt.Printf("%p
    ", GetSingle())
    	fmt.Printf("%p
    ", 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
    ", GetSingle2())
    	go fmt.Printf("%p
    ", GetSingle2())
    	go fmt.Printf("%p
    ", 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
    ", GetSingle2())
    	go fmt.Printf("%p
    ", GetSingle2())
    	go fmt.Printf("%p
    ", 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
    ", GetSingle3())
    	go fmt.Printf("%p
    ", GetSingle3())
    	go fmt.Printf("%p
    ", GetSingle3())
    	time.Sleep(time.Second)
    	fmt.Println("done")
    }
    
  • 相关阅读:
    python 打包模块:nuitka
    模型量化
    .Net Core 起步
    adobe flash retired forever
    时间格式(全)
    Python使用chorm对ClickHouse简单查询及写入
    利用iFFT还原的图片有毛刺
    本人Linux常用命令
    Exp8 web综合
    Git 分支管理规范
  • 原文地址:https://www.cnblogs.com/daryl-blog/p/11369614.html
Copyright © 2020-2023  润新知