思路阐述
- 代理模式原理:代理模式通过创建一个代理对象来控制对目标对象(这里是
DataModel
实例)的访问。代理对象可以在访问目标对象的属性时,添加额外的逻辑,如缓存、日志记录等,从而实现性能优化。
- 结合getter和setter:利用代理对象拦截对
DataModel
属性的访问和修改操作。对于getter方法,在代理中可以实现缓存机制,避免重复获取相同的数据。对于setter方法,代理可以进行数据验证或触发相关的更新操作,确保数据的一致性和正确性。
关键代码示例
// 数据模型类
class DataModel {
constructor() {
this.property1 = 'value1';
this.property2 = 'value2';
}
get property1() {
return this._property1;
}
set property1(value) {
this._property1 = value;
}
get property2() {
return this._property2;
}
set property2(value) {
this._property2 = value;
}
}
// 创建代理对象
const dataModel = new DataModel();
const dataModelProxy = new Proxy(dataModel, {
// 缓存对象
cache: {},
get(target, property) {
if (this.cache[property]) {
return this.cache[property];
}
const value = target[property];
this.cache[property] = value;
return value;
},
set(target, property, value) {
// 数据验证
if (property === 'property1' && typeof value!=='string') {
throw new Error('property1 must be a string');
}
target[property] = value;
// 清除相关缓存
delete this.cache[property];
return true;
}
});
// 使用代理对象
console.log(dataModelProxy.property1); // 第一次访问,从原对象获取并缓存
console.log(dataModelProxy.property1); // 第二次访问,直接从缓存获取
dataModelProxy.property1 = 'new value'; // 设置属性值,验证并清除缓存