• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1/*
2 * Copyright (c) 2023-2023 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15import { Log } from './Log';
16
17const TAG: string = 'GlobalObject';
18/**
19 * 构造单利对象,提供全局变量缓存代替globalThis
20 */
21export class GlobalObject {
22  private static instance: GlobalObject;
23  private _objects = new Map<string, Object>();
24
25  private constructor() {
26  }
27
28  /**
29   * 获取全局单个实例方法
30   *
31   * @returns instance instance
32   */
33  public static getInstance(): GlobalObject {
34    if (GlobalObject.instance == null) {
35      GlobalObject.instance = new GlobalObject();
36    }
37    return GlobalObject.instance;
38  }
39
40  /**
41   * 从Map中返回指定的元素
42   *
43   * @param key key
44   * @returns 返回指定key的元素,获取不到返回undefined
45   */
46  public getObject(key: string): Object | undefined {
47    let result = this._objects.get(key);
48    Log.info(TAG, 'getValue: ' + key + ' -> ' + (result != null));
49    return result;
50  }
51
52  /**
53   * 将指定键和值添加到Map中。如果已存在相同元素,则更新元素
54   *
55   * @param key map中映射的唯一标记
56   * @param objectClass 需要存储的元素
57   */
58  public setObject(key: string, objectClass: Object): void {
59    this._objects.set(key, objectClass);
60    Log.info(TAG, 'setObject: ' + key);
61  }
62
63  /**
64   * 从Map中移除指定元素
65   *
66   * @param key map中映射的唯一标记
67   * @returns 是否成功移除key对应元素
68   */
69  public removeObject(key: string): boolean {
70    Log.info(TAG, 'delete: ' + key);
71    return this._objects.delete(key);
72  }
73
74  /**
75   * 判断从Map中是否存在指定元素
76   *
77   * @param key map中映射的唯一标记
78   * @returns 存在返回true
79   */
80  public hasObject(key: string): boolean {
81    return this._objects.has(key);
82  }
83}