rts-sim-module/modelrepo/manage.go

58 lines
1.0 KiB
Go
Raw Normal View History

package modelrepo
2023-12-27 15:59:46 +08:00
import "sync"
2023-12-27 15:59:46 +08:00
// Repo管理
type repoManager struct {
repoMap map[string]Repo
lock sync.Mutex
}
2023-12-27 15:59:46 +08:00
var defaultManager = &repoManager{
repoMap: make(map[string]Repo),
}
// 获取Repo
func GetRepo(id string) Repo {
manager := defaultManager
manager.lock.Lock()
defer manager.lock.Unlock()
r, ok := manager.repoMap[id]
if !ok {
return nil
}
return r
}
// 保存Repo
func SaveRepo(r Repo) {
manager := defaultManager
manager.lock.Lock()
defer manager.lock.Unlock()
manager.repoMap[r.Id()] = r
}
// 移除Repo
func RemoveRepo(id string) {
manager := defaultManager
manager.lock.Lock()
defer manager.lock.Unlock()
delete(manager.repoMap, id)
}
// 获取或构建Repo,若存在则返回已存在的,若不存在则构建保存并返回
func GetOrBuildRepo(id string, builder func() (Repo, error)) (Repo, error) {
r := GetRepo(id)
if r == nil {
// 构建模型Repo
r, err := builder()
// 构建出错直接返回
if err != nil {
return nil, err
}
// 保存
SaveRepo(r)
}
return r, nil
}