import { Constructor } from "cc" // 打包之后有问题不支持名称注入 export class SingletonAnnotation { private static TypeMap = new Map private static initNameMap = new Map() private static initTypeMap = new Map() static setSingleton(_obj?: { type?: any, consParam?: any } | string) { return function (target: any) { // 首字母小写注入 let consParam = _obj['consParam'] || {} SingletonAnnotation.initTypeMap.set(target, { target: target, consParam: consParam }); if (typeof _obj == "string") { SingletonAnnotation.initNameMap.set(_obj, { target: target, consParam: consParam }); } } } private static create(target: any, _obj?: { target?: any, consParam?: any }) { let consParam = _obj.consParam const instance = new target(); Object.keys(consParam).forEach((key) => { if (typeof key == "string") { if (instance.hasOwnProperty(key)) { instance[key] = consParam[key] } } }) if (SingletonAnnotation.TypeMap.has(target)) { console.error("有重复类型被注入") } SingletonAnnotation.TypeMap.set(target, instance); return instance } static getSingleton(name?: string | Constructor) { let res: PropertyDecorator = function (target, prop: string, desc?) { // 首字母小写注入 let value: any // 是否初始化 let init; return { get() { if (!init) { init = true if (!name) { name = prop } value = SingletonAnnotation.getValue(name) } return value }, set(v) { value = v }, } } return res } static getValue(name?: any) { if (!name) { return undefined; } let value if (typeof name != "string") { value = this.initObjByType(name); } else { value = this.initObjByName(name); } return value } private static initObjByName(name: string) { let v let param = SingletonAnnotation.initNameMap.get(name) if (param) { v = this.initObjByType(param.target) } return v } private static initObjByType(name: Constructor) { let v = SingletonAnnotation.TypeMap.get(name) if (!v) { let param = SingletonAnnotation.initTypeMap.get(name) if (param) { v = SingletonAnnotation.create(param.target, param) } } return v } static logInfo() { console.log("TypeMap", SingletonAnnotation.TypeMap) console.log("initTypeMap", SingletonAnnotation.initTypeMap) } }