type CacheValue = string | number | boolean | object;
/**
* 全局上下文管理类,用于存储和管理全局数据。
* author: 鸿蒙布道师
* since: 2025/04/15
*/
export class GlobalContext {
private static instance: GlobalContext;
private _objects = new Map<string, CacheValue>();
// 私有构造函数,防止外部实例化
private constructor() {}
/**
* 获取全局上下文实例(单例模式)。
* @returns 全局上下文实例
*/
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
/**
* 存储数据到缓存中。
* @param key - 数据键名
* @param value - 数据值
*/
public set<T extends CacheValue>(key: string, value: T): void {
this._objects.set(key, value);
}
/**
* 从缓存中获取数据。
* @param key - 数据键名
* @param defaultValue - 如果数据不存在时的默认值
* @returns 缓存中的数据或默认值
*/
public get<T extends CacheValue>(key: string, defaultValue?: T): T {
return this._objects.has(key)
? (this._objects.get(key) as T)
: (defaultValue as T);
}
/**
* 检查缓存中是否存在指定的数据。
* @param key - 数据键名
* @returns 如果存在返回 true,否则返回 false
*/
public has(key: string): boolean {
return this._objects.has(key);
}
/**
* 从缓存中移除指定的数据。
* @param key - 数据键名
*/
public remove(key: string): void {
this._objects.delete(key);
}
/**
* 清空所有缓存数据。
*/
public clear(): void {
this._objects.clear();
}
}
代码如下:
TypeScript
type CacheValue = string | number | boolean | object;
/**
* 全局上下文管理类,用于存储和管理全局数据。
* author: 鸿蒙布道师
* since: 2025/04/15
*/
export class GlobalContext {
private static instance: GlobalContext;
private _objects = new Map<string, CacheValue>();
// 私有构造函数,防止外部实例化
private constructor() {}
/**
* 获取全局上下文实例(单例模式)。
* @returns 全局上下文实例
*/
public static getContext(): GlobalContext {
if (!GlobalContext.instance) {
GlobalContext.instance = new GlobalContext();
}
return GlobalContext.instance;
}
/**
* 存储数据到缓存中。
* @param key - 数据键名
* @param value - 数据值
*/
public set<T extends CacheValue>(key: string, value: T): void {
this._objects.set(key, value);
}
/**
* 从缓存中获取数据。
* @param key - 数据键名
* @param defaultValue - 如果数据不存在时的默认值
* @returns 缓存中的数据或默认值
*/
public get<T extends CacheValue>(key: string, defaultValue?: T): T {
return this._objects.has(key)
? (this._objects.get(key) as T)
: (defaultValue as T);
}
/**
* 检查缓存中是否存在指定的数据。
* @param key - 数据键名
* @returns 如果存在返回 true,否则返回 false
*/
public has(key: string): boolean {
return this._objects.has(key);
}
/**
* 从缓存中移除指定的数据。
* @param key - 数据键名
*/
public remove(key: string): void {
this._objects.delete(key);
}
/**
* 清空所有缓存数据。
*/
public clear(): void {
this._objects.clear();
}
}