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 }