内容简介:1.非线程安全,虽然说是单例模式,但是如果实例以下是参考他人的方法。思路很好3.避免了每次加锁,提高了代码效率
Golang 单例模式的几种形式
1.非线程安全,虽然说是单例模式,但是如果实例 正在创建中 ,此时多个线程同时访问,就会获得多个结果
package main
var instance *Singleton
type Singleton struct {
}
func Instance() *Singleton{
if instance == nil {
instance = &Singleton{}
}
return instance
}
- 加锁单例模式
package main
import "sync"
var (
instance *Singleton
mu sync.Mutex
)
type Singleton struct {
}
func Instance() *Singleton{
mu.Lock()
defer mu.Unlock()
if instance == nil {
instance = &Singleton{}
}
return instance
}
以下是参考他人的方法。思路很好
3.避免了每次加锁,提高了代码效率
package main
import "sync"
var (
instance *Singleton
mu sync.Mutex
)
type Singleton struct {
}
func Instance() *Singleton {
if instance == nil {
mu.Lock()
defer mu.Unlock()
if instance == nil {
instance = &Singleton{}
}
}
return instance
}
4. once
实现
package main
import "sync"
var (
instance *Singleton
once sync.Once
)
type Singleton struct {
}
func Instance() *Singleton {
once.Do(func() {
instance = &Singleton{}
})
return instance
}
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 设计模式——订阅模式(观察者模式)
- 设计模式-简单工厂、工厂方法模式、抽象工厂模式
- java23种设计模式-门面模式(外观模式)
- 简单工厂模式、工厂模式、抽象工厂模式的解析-iOS
- Java 设计模式之工厂方法模式与抽象工厂模式
- JAVA设计模式之模板方法模式和建造者模式
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
The Art of Computer Programming, Volume 3
Donald E. Knuth / Addison-Wesley Professional / 1998-05-04 / USD 74.99
Finally, after a wait of more than thirty-five years, the first part of Volume 4 is at last ready for publication. Check out the boxed set that brings together Volumes 1 - 4A in one elegant case, and ......一起来看看 《The Art of Computer Programming, Volume 3》 这本书的介绍吧!