golang单例模式的优雅实现

sync.Once可以保证一个Once实例的Do方法只会执行一次,无论Do里的func有多个或者一个,利用这个特性来实现设计模式里的单例模式,注意要确保执行Do的Once实例是同一个。golang里没有类的说法,所以拿结构体来做测试,将结构体指针变量在Do的内进行初始化赋值后export给外部模块:

type singleton struct{}

var ins *singleton

var once sync.Once

func GetIns() *singleton {

    once.Do(func(){

        ins = &singleton{}            

      //ins = new(singleton)})

    })

    return ins

}


sync.Once doc:

type Once

Once is an object that will perform exactly one action.

type Once struct {

    // contains filtered or unexported fields

}

func (*Once) Do

func (o *Once) Do(f func())

Do calls the function f if and only if Do is being called for the first time for this instance of Once. In other words, given

var once Once

if once.Do(f) is called multiple times, only the first call will invoke f, even if f has a different value in each invocation. A new instance of Once is required for each function to execute.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,052评论 0 38
  • "use strict";function _classCallCheck(e,t){if(!(e instanc...
    久些阅读 2,068评论 0 2
  • 01.{ 换行: Opening Brace Can't Be Placed on a Separate Lin...
    码农不器阅读 2,437评论 0 14
  • “我那辆爱玛电动车现在基本没骑,我弟弟捡去用了。 身边玩的那些人,都是开着车的。我能走路的走路,走不了的打摩托车或...
    夏奈l阅读 381评论 0 0
  • 醉美的夜色 我轻轻的记录下此刻的心情 沧桑 孤独 不知道远方的你的心 是否关闭了爱情的大门 寒风刺骨 你的风衣是否...
    落日余岸阅读 169评论 0 0