Açıklama Yok
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

container_factory.go 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. // container_factory.go
  2. package container
  3. import (
  4. "log"
  5. "sync"
  6. "git.x2erp.com/qdy/go-base/config"
  7. )
  8. type Resource interface {
  9. GetName() string
  10. Close()
  11. }
  12. type CreateFunc[T Resource] func(cfg config.IConfig) T
  13. type ContainerFactory struct {
  14. config config.IConfig
  15. resources map[string]Resource // 用map按名称存储
  16. order []string // 保持添加顺序
  17. mu sync.RWMutex
  18. }
  19. func NewContainer(cfg config.IConfig) *ContainerFactory {
  20. return &ContainerFactory{
  21. config: cfg,
  22. resources: make(map[string]Resource),
  23. order: make([]string, 0),
  24. }
  25. }
  26. // 泛型方法:如果不存在则创建并注册
  27. func Create[T Resource](c *ContainerFactory, createFunc CreateFunc[T]) T {
  28. //c.mu.Lock()
  29. //defer c.mu.Unlock()
  30. // 先创建对象获取名称
  31. resource := createFunc(c.config)
  32. return Reg(c, resource)
  33. // name := resource.GetName()
  34. // log.Printf("创建 %s 对象", name)
  35. // // 如果已存在,返回已注册的对象
  36. // if existing, ok := c.resources[name]; ok {
  37. // log.Printf("对象 %s 已经存在.", name)
  38. // return existing.(T) // 安全,因为同名的类型肯定相同
  39. // }
  40. // log.Printf("缓存 %s 对象", name)
  41. // // 添加到order(保持顺序)
  42. // c.order = append(c.order, name)
  43. // // 存储到map
  44. // c.resources[name] = resource
  45. // return resource
  46. }
  47. // / Reg 直接注册已创建的对象
  48. func Reg[T Resource](c *ContainerFactory, resource T) T {
  49. c.mu.Lock()
  50. defer c.mu.Unlock()
  51. name := resource.GetName()
  52. log.Printf("直接注册 %s 对象", name)
  53. // 如果已存在,返回已注册的对象(或报错)
  54. if existing, ok := c.resources[name]; ok {
  55. log.Printf("对象 %s 已经存在,跳过注册", name)
  56. // 可以选择返回已有的对象或什么都不做
  57. return existing.(T) // 安全,因为同名的类型肯定相同
  58. }
  59. log.Printf("缓存 %s 对象", name)
  60. // 添加到order(保持顺序)
  61. c.order = append(c.order, name)
  62. // 存储到map
  63. c.resources[name] = resource
  64. log.Printf("已注册 %s 对象", name)
  65. return resource
  66. }
  67. // 按添加顺序关闭(先进先出,最先添加的最先关闭)
  68. func (c *ContainerFactory) CloseAll() {
  69. c.mu.Lock()
  70. defer c.mu.Unlock()
  71. // 按添加顺序关闭
  72. for _, name := range c.order {
  73. if res, ok := c.resources[name]; ok {
  74. res.Close()
  75. log.Printf("关闭 %s 对象", name)
  76. }
  77. }
  78. // 清空容器
  79. c.resources = make(map[string]Resource)
  80. c.order = make([]string, 0)
  81. }