一)golang的单例模式

栏目: Go · 发布时间: 5年前

内容简介:在23种设计模式中,单例模式作为最普遍运用的设计模式之一,在软件开发中起着非常重要的地位。应用场景:对资源单一且有严格控制的场景,例如. 数据库连接类对象:可一次创建,一直使用的类

在23种 设计模式 中,单例模式作为最普遍运用的设计模式之一,在软件开发中起着非常重要的地位。

应用场景:对资源单一且有严格控制的场景,例如. 数据库连接类

对象:可一次创建,一直使用的类

在golang中的单例模式实现方式有多种,但需要效率的实现主要还是依赖于 sync/Once 实现,其实现原理主要是依赖于 sync/atomic 包的原子操作源代码如下

type Once struct {
    m    Mutex
    done uint32
}
func (o *Once) Do(f func()) {
    if atomic.LoadUint32(&o.done) == 1 {
        return
    }
    // Slow-path.
    o.m.Lock()
    defer o.m.Unlock()
    if o.done == 0 {
        defer atomic.StoreUint32(&o.done, 1)
        f()
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

The Nature of Code

The Nature of Code

Daniel Shiffman / The Nature of Code / 2012-12-13 / GBP 19.95

How can we capture the unpredictable evolutionary and emergent properties of nature in software? How can understanding the mathematical principles behind our physical world help us to create digital w......一起来看看 《The Nature of Code》 这本书的介绍吧!

Base64 编码/解码
Base64 编码/解码

Base64 编码/解码

URL 编码/解码
URL 编码/解码

URL 编码/解码

XML 在线格式化
XML 在线格式化

在线 XML 格式化压缩工具