| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115 |
- import { Constructor } from "cc"
- // 打包之后有问题不支持名称注入
- export class SingletonAnnotation {
- private static TypeMap = new Map
- private static initNameMap = new Map<string, { target: any, consParam?: any }>()
- private static initTypeMap = new Map<any, { target: any, consParam?: any }>()
- 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)
- }
- }
|