ModelManager.ts 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /**
  2. * 数据模型管理类
  3. */
  4. import BaseModel from "../base/BaseModel";
  5. export default class ModelManager {
  6. /** 实例 */
  7. private static _instance: ModelManager = new ModelManager();
  8. /** 数据model集合 */
  9. private _modelList: {};
  10. /**
  11. * @constructor
  12. * @private
  13. */
  14. private constructor () {
  15. this._modelList = {};
  16. }
  17. /**
  18. * 单例获取类
  19. */
  20. public static getInstance(): ModelManager {
  21. return this._instance;
  22. }
  23. /**
  24. * 获取model对象
  25. * @param {{new (): BaseModel}} model
  26. */
  27. public getModel<T extends BaseModel>(model: {new (): T}): T {
  28. let key = cc.js.getClassName(model);
  29. return this._modelList[key];
  30. }
  31. /**
  32. * 注册数据model
  33. * @param {{new (): BaseModel}} model
  34. */
  35. public registerModel(model: {new (): BaseModel}): void {
  36. let key = cc.js.getClassName(model);
  37. if (this._modelList.hasOwnProperty(key)) {
  38. console.log(key, "已经存在,不可重复注册!");
  39. } else {
  40. let m = new model();
  41. m.init();
  42. this._modelList[key] = m;
  43. }
  44. }
  45. /**
  46. * 移除注册
  47. * @param {{new (): BaseModel}} model
  48. */
  49. public unregisterModel(model: {new (): BaseModel}): void {
  50. let key = cc.js.getClassName(model);
  51. if (this._modelList.hasOwnProperty(key)) {
  52. let m: BaseModel = this._modelList[key];
  53. m.clear();
  54. delete this._modelList[key];
  55. } else {
  56. console.warn(key, "不存在!");
  57. }
  58. }
  59. /**
  60. * 释放并移除所有model
  61. */
  62. public removeAllModel(): void {
  63. // 释放并移除所有model
  64. for (let key in this._modelList) {
  65. let model: BaseModel = this._modelList[key];
  66. model.clear();
  67. delete this._modelList[key];
  68. }
  69. this._modelList = {};
  70. }
  71. }