设计思路
- 性能监控:通过装饰器在方法执行前后记录时间,计算执行时间并打印或上报。
- 权限控制:检查当前用户权限,决定方法是否可执行。
- 日志记录:记录方法的调用信息,如参数、返回值等。
- 兼容性与顺序:确保装饰器能按特定顺序执行,互不干扰。
- 配置与管理:通过配置文件或统一的管理方式,决定哪些组件方法应用哪些装饰器。
关键代码示例
// 性能监控装饰器
function performanceMonitor(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
const start = Date.now();
const result = originalMethod.apply(this, args);
const end = Date.now();
console.log(`Method ${propertyKey} took ${end - start} ms to execute`);
return result;
};
return descriptor;
}
// 权限控制装饰器
function permissionControl(requiredPermission: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
// 模拟获取当前用户权限
const currentUserPermissions = ['admin', 'user'];
if (currentUserPermissions.includes(requiredPermission)) {
return originalMethod.apply(this, args);
} else {
console.log('Permission denied');
}
};
return descriptor;
};
}
// 日志记录装饰器
function log(target: any, propertyKey: string, descriptor: PropertyDescriptor) {
const originalMethod = descriptor.value;
descriptor.value = function (...args: any[]) {
console.log(`Calling method ${propertyKey} with args:`, args);
const result = originalMethod.apply(this, args);
console.log(`Method ${propertyKey} returned:`, result);
return result;
};
return descriptor;
}
class MyComponent {
@performanceMonitor
@permissionControl('admin')
@log
myMethod() {
// 模拟业务逻辑
console.log('My method is running');
}
}
const component = new MyComponent();
component.myMethod();
配置与管理
- 配置文件:可以创建一个 JSON 或 YAML 配置文件,指定每个组件类及其方法需要应用的装饰器。
- 统一管理:在项目入口或特定的配置模块中,根据配置文件加载和应用装饰器,确保装饰器的应用在整个项目中保持一致。