douhuang2218 2017-11-30 09:53
浏览 29

如何在Golang中设置继承

tl;dr

What is the right way to set Store to be shared between multiple services in this example: https://github.com/th0th/goblog/blob/2b2d7ac51978de41f392396309424043817a49d7/store/store.go#L29

Details

Greetings, I am trying to comprehend how go works by creating a simple MVC-ish blog REST API. I have planned the application to consist of 3 packages/layers:

models

Holds the structs of data. Defines the interfaces for database access layers of these structs.

store

Presents the actual database connections. Implements the interfaces from models. All database access is done through this implementation.

api

REST API related stuff. Routes and such.

I have a Store struct in store package, which holds the services:

// Store wraps all services
type Store struct {
    DB *sqlx.DB

    CategoryService CategoryService
    PostService PostService
}

And here is the CategoryService (PostService is also like this. They both have methods for CRUD actions.):

// CategoryService represents a service for managing categories.
type CategoryService struct {
    store *Store
}

When I create an instance of this Store, I need to set store of every single service.

// New creates and returns new Store
func New() Store {
    var s Store

    db, err := sqlx.Connect("mysql", "<user>:<pass>@(localhost:3306)/goblog")

    if err != nil {
        log.Fatal(err)
    }

    s.DB = db

    s.CategoryService.store = &s
    s.PostService.store = &s

    return s
}

I want store to be shared between services, what is the correct approach? Am I doing something wrong?

  • 写回答

1条回答 默认 最新

  • douyuanqia665858 2017-12-02 20:32
    关注

    I find a bit strange in your design that the Store knows about the services and the services know about the Store...to me that double dependency does not look right, but that's probably subject to debate.

    If I were you, I would remove the services from the Store and pass the Store as parameter when you create the each service.

    For example, remove the services from the store:

    type Store struct {
      DB *sqlx.DB
      // no services here
    }
    

    ...and pass the Store as a parameter when you create the service:

    type CategoryService struct {
      store *Store
    }
    
    func NewCategoryService(s Store) CategoryService {
      var service CategoryService
      service.store = s
      return service
    }
    
    func (service CategoryService) Add()  {
      // service will have access to the store value
      // via service.store
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?