duanbin198788 2014-07-05 06:08
浏览 149
已采纳

我应该避免在golang中打包单例吗?

at the moment I have a package store with following content:

package store

var (
    db *Database
)

func Open(url string) error {
    // open db connection
}

func FindAll(model interface{}) error {
    // return all entries
}

func Close() {
    // close db connection
}

This allows me to use store.FindAll from other packages after I have done store.Open in main.go.

However as I saw so far most packages prefer to provide a struct you need to initialize yourself. There are only few cases where this global approach is used.

What are downsides of this approach and should I avoid it?

  • 写回答

2条回答 默认 最新

  • doushuo8677 2014-07-06 02:13
    关注

    The standard http package has a ServerMux for generic usecases and but also has one default instance of ServerMux called DefaultServerMux (http://golang.org/pkg/net/http/#pkg-variables) for convenience. So that when you call http.HandleFunc it creates the handler on the default mux. You can find the same approach used in log and many other packages. This is essentially your "singleton" approach.

    However, I don't think it's a good idea to follow that pattern in your use case, since the users need to call Open regardless of the default database. And, because of that, using a default instance would not really help and instead would actually make it less convenient:

    d := store.Open(...)
    defer d.Close()
    d.FindAll(...)
    

    is much easier to both write and read than:

    store.Open(...)
    defer store.Close()
    store.FindAll(...)
    

    And, also there are semantic problems: what should happen if someone calls Open twice:

    store.Open(...)
    defer store.Close()
    ...
    store.Open(...)
    store.FindAll(...) // Which db is this referring to?
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?