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.

85 lines
2.5 KiB

3 years ago
  1. // Copyright (c) Shenyang Leading Edge Intelligent Technology Co., Ltd. All rights reserved.
  2. package container
  3. import (
  4. "errors"
  5. "fmt"
  6. "reflect"
  7. "strings"
  8. )
  9. // 组件实例工厂
  10. type Factory reflect.Value
  11. // 设置字段值
  12. // 参数
  13. // 1.需要设置字段值的实例
  14. // 2.可以设置的类型和值的映射
  15. // 返回值:
  16. // 1.错误
  17. func (factory Factory) setReferences(instance reflect.Value, references map[reflect.Type]reflect.Value) error {
  18. implement := reflect.ValueOf(instance.Interface())
  19. implementPointerType := implement.Type()
  20. implementType := implementPointerType.Elem()
  21. for i := 0; i < implementType.NumField(); i++ {
  22. field := implementType.Field(i)
  23. if reference, ok := references[field.Type]; ok {
  24. methodName := fmt.Sprintf("Set%s", strings.Title(field.Name))
  25. method, ok := implementPointerType.MethodByName(methodName)
  26. if ok {
  27. methodType := method.Type // 从结构体指针类型获取方法类型,Receiver算作入参
  28. if methodType.NumIn() != 2 {
  29. return errors.New(fmt.Sprintf("设置器参数数量不正确!"))
  30. }
  31. if methodType.NumOut() != 0 {
  32. return errors.New(fmt.Sprintf("设置器返回值数量不正确!"))
  33. }
  34. if methodType.In(1) != field.Type {
  35. return errors.New(fmt.Sprintf("设置器类型不正确!"))
  36. }
  37. implement.MethodByName(methodName).Call([]reflect.Value{reference})
  38. }
  39. }
  40. }
  41. return nil
  42. }
  43. // 创建实例
  44. // 参数
  45. // 1.会话上下文
  46. // 返回值:
  47. // 1.调用器
  48. // 2.错误
  49. func (factory Factory) Create(context *SessionContext) (Instance, error) {
  50. if context == nil {
  51. return ZeroInstance, errors.New(fmt.Sprintf("会话上下文不能为空!"))
  52. }
  53. instanceValue := reflect.Value(factory).Call(emptyParameters)[0]
  54. actualValue := instanceValue
  55. if instanceValue.Kind() == reflect.Interface {
  56. actualValue = reflect.ValueOf(instanceValue.Interface())
  57. }
  58. // 检查空接口
  59. if actualValue.Kind() == reflect.Invalid {
  60. return ZeroInstance, errors.New(fmt.Sprintf("实际值不能是空接口!"))
  61. }
  62. if actualValue.Kind() != reflect.Ptr {
  63. return Instance(instanceValue), nil
  64. }
  65. // 检查空指针,首先要保证是指针
  66. if actualValue.IsNil() {
  67. return ZeroInstance, errors.New(fmt.Sprintf("实际值不能是空指针!"))
  68. }
  69. actualType := actualValue.Type()
  70. if actualType.Elem().Kind() != reflect.Struct {
  71. return Instance(instanceValue), nil
  72. }
  73. err := factory.setReferences(actualValue, map[reflect.Type]reflect.Value{sessionContextType: reflect.ValueOf(context)})
  74. if err != nil {
  75. return ZeroInstance, err
  76. }
  77. return Instance(instanceValue), nil
  78. }