HarmonyOS学习 - 装饰器模式
·
// 组件接口
interface Component {
operation(): string
}
// 具体组件类
class ConcreteComponent implements Component {
operation(): string {
return 'ConcreteComponent operation'
}
}
// 装饰器抽象类
abstract class Decorator implements Component {
protected component: Component
constructor(component: Component) {
this.component = component
}
abstract operation(): string
}
// 具体装饰器类 A
class ConcreteDecoratorA extends Decorator {
operation(): string {
return `ConcreteDecoratorA(${this.component.operation()})`
}
}
// 具体装饰器类 B
class ConcreteDecoratorB extends Decorator {
operation(): string {
return `ConcreteDecoratorB(${this.component.operation()})`
}
}
export { ConcreteComponent, ConcreteDecoratorA, ConcreteDecoratorB }
- 原理:装饰器模式允许向一个现有的对象添加新的功能,同时又不改变其结构。它通过创建一个装饰器类,来包装原有的类,并在保持类方法签名完整性的前提下,提供了额外的功能。
- 代码流程:
Component接口定义了组件的公共方法operation()。ConcreteComponent是具体的组件类,实现了Component接口。Decorator是装饰器抽象类,它实现了Component接口,并持有一个Component类型的引用component。ConcreteDecoratorA和ConcreteDecoratorB是具体的装饰器类,它们继承自Decorator类,并在operation()方法中调用被装饰对象的operation()方法,同时添加自己的额外功能。
更多推荐


所有评论(0)