实现思路
- 定义基础类
BaseClass
:包含通用的属性和方法。
- 使用装饰器:通过装饰器来动态修改或扩展子类的行为。装饰器可以接收配置参数,根据参数来决定如何修改子类。
- 创建子类:继承自
BaseClass
,并应用装饰器来根据配置调整行为。
关键要点
- 装饰器参数:正确传递和解析装饰器的配置参数,以决定如何进行行为修改。
- 方法重写与新增:在装饰器内部实现对现有方法的修改逻辑,以及新增方法的逻辑。
- 继承关系:确保子类能正确继承
BaseClass
的属性和方法,并在装饰器作用下扩展或修改行为。
代码示例
// 基础类
class BaseClass {
commonMethod() {
console.log('This is a common method in BaseClass');
}
}
// 装饰器工厂函数,接收配置参数
function modifyClass(config: { newMethod?: boolean, overrideMethod?: boolean }) {
return function <T extends { new(...args: any[]): {} }>(constructor: T) {
return class extends constructor {
constructor(...args: any[]) {
super(...args);
if (config.newMethod) {
// 新增方法
this.newMethod = function () {
console.log('This is a new method added by decorator');
};
}
if (config.overrideMethod) {
// 重写方法
const originalCommonMethod = this.commonMethod.bind(this);
this.commonMethod = function () {
console.log('Override: Before original method');
originalCommonMethod();
console.log('Override: After original method');
};
}
}
};
};
}
// 创建子类并应用装饰器
@modifyClass({ newMethod: true, overrideMethod: true })
class SubClass extends BaseClass {}
// 测试
const subClassInstance = new SubClass();
subClassInstance.commonMethod();
if ('newMethod' in subClassInstance) {
(subClassInstance as any).newMethod();
}