SingletonAnnotation.ts 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. import { Constructor } from "cc"
  2. // 打包之后有问题不支持名称注入
  3. export class SingletonAnnotation {
  4. private static TypeMap = new Map
  5. private static initNameMap = new Map<string, { target: any, consParam?: any }>()
  6. private static initTypeMap = new Map<any, { target: any, consParam?: any }>()
  7. static setSingleton(_obj?: { type?: any, consParam?: any } | string) {
  8. return function (target: any) {
  9. // 首字母小写注入
  10. let consParam = _obj['consParam'] || {}
  11. SingletonAnnotation.initTypeMap.set(target, { target: target, consParam: consParam });
  12. if (typeof _obj == "string") {
  13. SingletonAnnotation.initNameMap.set(_obj, { target: target, consParam: consParam });
  14. }
  15. }
  16. }
  17. private static create(target: any, _obj?: { target?: any, consParam?: any }) {
  18. let consParam = _obj.consParam
  19. const instance = new target();
  20. Object.keys(consParam).forEach((key) => {
  21. if (typeof key == "string") {
  22. if (instance.hasOwnProperty(key)) {
  23. instance[key] = consParam[key]
  24. }
  25. }
  26. })
  27. if (SingletonAnnotation.TypeMap.has(target)) {
  28. console.error("有重复类型被注入")
  29. }
  30. SingletonAnnotation.TypeMap.set(target, instance);
  31. return instance
  32. }
  33. static getSingleton(name?: string | Constructor) {
  34. let res: PropertyDecorator = function (target, prop: string, desc?) {
  35. // 首字母小写注入
  36. let value: any
  37. // 是否初始化
  38. let init;
  39. return {
  40. get() {
  41. if (!init) {
  42. init = true
  43. if (!name) {
  44. name = prop
  45. }
  46. value = SingletonAnnotation.getValue(name)
  47. }
  48. return value
  49. },
  50. set(v) { value = v },
  51. }
  52. }
  53. return res
  54. }
  55. static getValue(name?: any) {
  56. if (!name) {
  57. return undefined;
  58. }
  59. let value
  60. if (typeof name != "string") {
  61. value = this.initObjByType(name);
  62. } else {
  63. value = this.initObjByName(name);
  64. }
  65. return value
  66. }
  67. private static initObjByName(name: string) {
  68. let v
  69. let param = SingletonAnnotation.initNameMap.get(name)
  70. if (param) {
  71. v = this.initObjByType(param.target)
  72. }
  73. return v
  74. }
  75. private static initObjByType(name: Constructor) {
  76. let v = SingletonAnnotation.TypeMap.get(name)
  77. if (!v) {
  78. let param = SingletonAnnotation.initTypeMap.get(name)
  79. if (param) {
  80. v = SingletonAnnotation.create(param.target, param)
  81. }
  82. }
  83. return v
  84. }
  85. static logInfo() {
  86. console.log("TypeMap", SingletonAnnotation.TypeMap)
  87. console.log("initTypeMap", SingletonAnnotation.initTypeMap)
  88. }
  89. }