The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
yujianwjj

go 单例模式

  •  
  •   yujianwjj · Jun 3, 2020 · 3834 views
    This topic created in 2358 days ago, the information mentioned may be changed or developed.
    type A struct {
        data int
    }
    
    var a = A{3}
    
    func Create() *A {
        return &a
    }
    

    这个是单例模式吗?

    9 replies  •  2020-06-08 10:53:07 +08:00
    luoqeng
    luoqeng
    Jun 3, 2020
    1
    package 级别的变量就是单例
    neoblackcap
    neoblackcap
    Jun 4, 2020
    2
    是,没记错你还可以用 init 函数对你的对象进行初始化
    janxin
    janxin
    Jun 4, 2020
    3
    你甚至可以使用 sync.Once
    coldmonkeybit
    coldmonkeybit
    Jun 4, 2020
    4
    请教一下,为什么这个算单例,我在其他地方不一样可以 new 这个 A 么..
    ziyeziye
    ziyeziye
    Jun 4, 2020
    5
    @coldmonkeybit 一个是新变量,一个是返回已有变量的指针
    PiersSoCool
    PiersSoCool
    Jun 4, 2020
    6
    package 级别的变量就是单例
    asAnotherJack
    asAnotherJack
    Jun 4, 2020
    7
    @coldmonkeybit #4 我也一直有这个疑问,像 Java 里单例第一步就是构造器 private,在外边根本就创建不了这个类的实例,但是 go 好像就只能凭使用者自觉了
    brucewuio
    brucewuio
    Jun 6, 2020❤️1
    8
    @asAnotherJack 你可以让 A 也不对外暴露,每次 Create 返回同一个
    asAnotherJack
    asAnotherJack
    Jun 8, 2020
    9
    @brucewuio #8 刚试了下,不对外暴露的 struct 居然可以有 public 的方法和字段,学到了。但是总感觉有点怪怪的……
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4811 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 83ms · UTC 02:00 · PVG 10:00 · LAX 18:00 · JFK 21:00
    ♥ Do have faith in what you're doing.