component.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package component
  2. import (
  3. "git.sxidc.com/go-tools/utils/strutils"
  4. "github.com/pkg/errors"
  5. "sync"
  6. )
  7. type Component interface {
  8. GetType() string
  9. GetName() string
  10. Run(globalRunParams *GlobalRunParams, dynamicParams map[string]any) (any, error)
  11. }
  12. type Builder interface {
  13. ProductType() string
  14. Build(name string, buildParams map[string]any, runParams map[string]any) (Component, error)
  15. }
  16. var nodeBuilderMap = sync.Map{}
  17. func RegisterComponentBuilders(builders ...Builder) error {
  18. if builders == nil || len(builders) == 0 {
  19. return nil
  20. }
  21. for _, builder := range builders {
  22. nodeType := builder.ProductType()
  23. if strutils.IsStringEmpty(nodeType) {
  24. return errors.New("节点类型名称不能为空")
  25. }
  26. _, ok := nodeBuilderMap.Load(nodeType)
  27. if ok {
  28. return errors.New(nodeType + "的builder已注册")
  29. }
  30. nodeBuilderMap.Store(nodeType, builder)
  31. }
  32. return nil
  33. }
  34. func UnRegisterComponents(typeNames []string) {
  35. if typeNames == nil || len(typeNames) == 0 {
  36. return
  37. }
  38. for _, typeName := range typeNames {
  39. nodeBuilderMap.Delete(typeName)
  40. }
  41. }
  42. func BuildComponent(typeName string, name string, buildParams map[string]any, runParams map[string]any) (Component, error) {
  43. if strutils.IsStringEmpty(typeName) {
  44. return nil, errors.New("没有传递类型名称")
  45. }
  46. if strutils.IsStringEmpty(name) {
  47. return nil, errors.New("没有传递名称")
  48. }
  49. value, ok := nodeBuilderMap.Load(typeName)
  50. if !ok {
  51. return nil, errors.New(typeName + "未注册")
  52. }
  53. builder, ok := value.(Builder)
  54. if !ok {
  55. return nil, errors.New(typeName + "类型转换失败")
  56. }
  57. newComponent, err := builder.Build(name, buildParams, runParams)
  58. if err != nil {
  59. return nil, err
  60. }
  61. if newComponent == nil {
  62. return nil, errors.New(typeName + "的builder返回的对象为空")
  63. }
  64. return newComponent, nil
  65. }