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 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示