import { util } from '@kit.ArkTS';/*** LRUCache緩存工具類(單例模式)* @author 鴻蒙布道師* @since 2025/04/21*/
export class LRUCacheUtil {private static instance: LRUCacheUtil;private lruCache: util.LRUCache<string, any>;/*** 私有構造函數,防止外部實例化*/private constructor() {this.lruCache = new util.LRUCache(64); // 默認容量為64}/*** 獲取LRUCacheUtil的單例* @returns LRUCacheUtil 單例對象*/public static getInstance(): LRUCacheUtil {if (!LRUCacheUtil.instance) {LRUCacheUtil.instance = new LRUCacheUtil();}return LRUCacheUtil.instance;}/*** 判斷是否包含指定key的緩存* @param key 緩存鍵* @returns 是否存在該key*/public has(key: string): boolean {return this.lruCache.contains(key);}/*** 獲取指定key的緩存值* @param key 緩存鍵* @returns 緩存值,若不存在則返回undefined*/public get<T = any>(key: string): T | undefined {return this.lruCache.get(key) as T;}/*** 添加或更新緩存* @param key 緩存鍵* @param value 緩存值*/public put(key: string, value: any): void {this.lruCache.put(key, value);}/*** 刪除指定key的緩存* @param key 緩存鍵*/public remove(key: string): void {this.lruCache.remove(key);}/*** 判斷緩存是否為空* @returns 是否為空*/public isEmpty(): boolean {return this.lruCache.isEmpty();}/*** 獲取當前緩存的容量* @returns 當前容量*/public getCapacity(): number {return this.lruCache.getCapacity();}/*** 更新緩存的容量* @param newCapacity 新的容量*/public updateCapacity(newCapacity: number): void {if (newCapacity <= 0) {throw new Error("Capacity must be greater than 0.");}this.lruCache.updateCapacity(newCapacity);}/*** 清空緩存并重置容量為默認值*/public clear(): void {this.lruCache.clear();this.lruCache.updateCapacity(64); // 重置為默認容量}
}
代碼如下:
import { util } from '@kit.ArkTS';/*** LRUCache緩存工具類(單例模式)* @author 鴻蒙布道師* @since 2025/04/21*/
export class LRUCacheUtil {private static instance: LRUCacheUtil;private lruCache: util.LRUCache<string, any>;/*** 私有構造函數,防止外部實例化*/private constructor() {this.lruCache = new util.LRUCache(64); // 默認容量為64}/*** 獲取LRUCacheUtil的單例* @returns LRUCacheUtil 單例對象*/public static getInstance(): LRUCacheUtil {if (!LRUCacheUtil.instance) {LRUCacheUtil.instance = new LRUCacheUtil();}return LRUCacheUtil.instance;}/*** 判斷是否包含指定key的緩存* @param key 緩存鍵* @returns 是否存在該key*/public has(key: string): boolean {return this.lruCache.contains(key);}/*** 獲取指定key的緩存值* @param key 緩存鍵* @returns 緩存值,若不存在則返回undefined*/public get<T = any>(key: string): T | undefined {return this.lruCache.get(key) as T;}/*** 添加或更新緩存* @param key 緩存鍵* @param value 緩存值*/public put(key: string, value: any): void {this.lruCache.put(key, value);}/*** 刪除指定key的緩存* @param key 緩存鍵*/public remove(key: string): void {this.lruCache.remove(key);}/*** 判斷緩存是否為空* @returns 是否為空*/public isEmpty(): boolean {return this.lruCache.isEmpty();}/*** 獲取當前緩存的容量* @returns 當前容量*/public getCapacity(): number {return this.lruCache.getCapacity();}/*** 更新緩存的容量* @param newCapacity 新的容量*/public updateCapacity(newCapacity: number): void {if (newCapacity <= 0) {throw new Error("Capacity must be greater than 0.");}this.lruCache.updateCapacity(newCapacity);}/*** 清空緩存并重置容量為默認值*/public clear(): void {this.lruCache.clear();this.lruCache.updateCapacity(64); // 重置為默認容量}
}