设计思路
- 利用一个对象来存储缓存结果,键为方法的参数组合,值为方法的返回结果。
- 创建一个方法装饰器,在装饰器内部检查缓存中是否已经存在对应参数的结果。如果存在,直接返回缓存结果;如果不存在,执行原始方法,将结果存入缓存,然后返回结果。
代码实现
// 缓存对象
const cache: Record<string, any> = {};
// 方法装饰器
function cacheDecorator(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const key = args.toString();
if (cache[key]) {
return cache[key];
}
const result = originalMethod.apply(this, args);
cache[key] = result;
return result;
};
return descriptor;
}
// 示例计算密集型方法
class Example {
@cacheDecorator
computeIntensiveMethod(a: number, b: number): number {
// 模拟计算密集型操作
let result = 0;
for (let i = 0; i < 1000000; i++) {
result += a * b + i;
}
return result;
}
}
// 使用示例
const example = new Example();
console.log(example.computeIntensiveMethod(2, 3)); // 第一次执行,计算并缓存
console.log(example.computeIntensiveMethod(2, 3)); // 第二次执行,直接从缓存获取