import { ObjectUtil } from './ObjectUtil';
/**
* 缓存工具类
*
* 该类提供了一组静态方法,用于操作缓存数据。
* 主要功能包括:获取缓存数据、存储缓存数据、删除缓存数据、检查键是否存在、判断缓存是否为空以及清空缓存。
*
* @author CSDN-鸿蒙布道师
* @since 2025/04/03
*/
export class CacheUtil {
private static cache: Record<string, Object> = {}; // 私有缓存对象
/**
* 获取缓存中的数据
*
* 根据指定的键从缓存中获取对应的值。如果键不存在,则返回 `undefined`。
*
* @param key - 存入的键
* @returns 缓存中的值,类型为泛型 T 或 undefined
*/
static get<T>(key: string): T | undefined {
const value = Reflect.get(CacheUtil.cache, key);
return value as T;
}
/**
* 将数据存入缓存中
*
* 将指定的键值对存入缓存中。如果键已存在,则会覆盖原有值。
*
* @param key - 存入的键
* @param value - 存入的数据
*/
static put<T>(key: string, value: T): void {
Reflect.set(CacheUtil.cache, key, value);
}
/**
* 删除对应的缓存
*
* 根据指定的键删除缓存中的对应数据。如果键不存在,则不会抛出错误。
*
* @param key - 要删除的键
*/
static remove(key: string): void {
ObjectUtil.deleteRecord(CacheUtil.cache, key);
}
/**
* 判断缓存中是否存在指定的键
*
* 检查缓存中是否包含指定的键。
*
* @param key - 要检查的键
* @returns 如果键存在,则返回 true;否则返回 false
*/
static has(key: string): boolean {
return Reflect.has(CacheUtil.cache, key);
}
/**
* 判断缓存是否为空
*
* 检查缓存中是否没有任何数据。
*
* @returns 如果缓存为空,则返回 true;否则返回 false
*/
static isEmpty(): boolean {
const keys = Object.keys(CacheUtil.cache);
return keys.length === 0;
}
/**
* 清除缓存数据
*
* 清空缓存中的所有数据。
*/
static clear(): void {
CacheUtil.cache = {};
}
}
代码如下:
import { ObjectUtil } from './ObjectUtil';
/**
* 缓存工具类
*
* 该类提供了一组静态方法,用于操作缓存数据。
* 主要功能包括:获取缓存数据、存储缓存数据、删除缓存数据、检查键是否存在、判断缓存是否为空以及清空缓存。
*
* @author CSDN-鸿蒙布道师
* @since 2025/04/03
*/
export class CacheUtil {
private static cache: Record<string, Object> = {}; // 私有缓存对象
/**
* 获取缓存中的数据
*
* 根据指定的键从缓存中获取对应的值。如果键不存在,则返回 `undefined`。
*
* @param key - 存入的键
* @returns 缓存中的值,类型为泛型 T 或 undefined
*/
static get<T>(key: string): T | undefined {
const value = Reflect.get(CacheUtil.cache, key);
return value as T;
}
/**
* 将数据存入缓存中
*
* 将指定的键值对存入缓存中。如果键已存在,则会覆盖原有值。
*
* @param key - 存入的键
* @param value - 存入的数据
*/
static put<T>(key: string, value: T): void {
Reflect.set(CacheUtil.cache, key, value);
}
/**
* 删除对应的缓存
*
* 根据指定的键删除缓存中的对应数据。如果键不存在,则不会抛出错误。
*
* @param key - 要删除的键
*/
static remove(key: string): void {
ObjectUtil.deleteRecord(CacheUtil.cache, key);
}
/**
* 判断缓存中是否存在指定的键
*
* 检查缓存中是否包含指定的键。
*
* @param key - 要检查的键
* @returns 如果键存在,则返回 true;否则返回 false
*/
static has(key: string): boolean {
return Reflect.has(CacheUtil.cache, key);
}
/**
* 判断缓存是否为空
*
* 检查缓存中是否没有任何数据。
*
* @returns 如果缓存为空,则返回 true;否则返回 false
*/
static isEmpty(): boolean {
const keys = Object.keys(CacheUtil.cache);
return keys.length === 0;
}
/**
* 清除缓存数据
*
* 清空缓存中的所有数据。
*/
static clear(): void {
CacheUtil.cache = {};
}
}