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

go 单例模式

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