用TS实现一种设计模式-修饰
时间: 2024-03-09 14:42:06 浏览: 26
修饰模式是一种结构型设计模式,它允许在不改变原始对象的情况下,动态地添加功能或修改行为。在 TypeScript 中实现修饰模式可以通过装饰器(Decorator)来实现。
装饰器是 TypeScript 提供的一种特殊类型的声明,它可以附加到类声明、方法、属性或参数上,以修改类的行为。在修饰模式中,我们可以定义一个基础类(Component),然后通过装饰器来扩展该类的功能。
下面是一个使用 TypeScript 实现修饰模式的示例:
```typescript
// 定义基础类
class Component {
operation(): void {
console.log("基础操作"); }
}
// 定义装饰器类
class Decorator extends Component {
private component: Component;
constructor(component: Component) {
super();
this.component = component;
}
operation(): void {
this.component.operation();
console.log("附加操作");
}
}
// 使用示例
const component = new Component();
const decorator = new Decorator(component);
decorator.operation();
```
在上面的示例中,`Component` 是基础类,`Decorator` 是装饰器类。装饰器类继承自基础类,在 `operation` 方法中调用基础类的 `operation` 方法,并添加了附加操作。
通过使用装饰器,我们可以动态地给基础类添加功能,而不需要修改基础类的代码。这样可以遵循开闭原则,使得代码更加灵活和可扩展。