rts-sim-module/modelrepo/manage.go
walker c4bc8c640f 重构singleton组件及相关方法接口
调整repo目录结构和命名
初步开始重构仿真实体加载
2023-12-28 16:49:28 +08:00

58 lines
1.0 KiB
Go

package modelrepo
import "sync"
// Repo管理
type repoManager struct {
repoMap map[string]Repo
lock sync.Mutex
}
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
}