装饰模式

  • 定义:动态的给一个对象添加一些额外的职责(俄罗斯套娃)

装饰模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 定义Component
interface Component {
operation():string
}
// 定义ConcreteComponent
class ConcreteComponent implements Component {
public operation() {
return "ConcreateComponent"
}
}
// 定义Base Decorator
class Decorator implements Component {
constructor(component:Component) {
this.component = component
}
operation() {
return this.component.operation()
}
}
// 定义具体装饰类
class ConcreteDecoratorA extends Decorator {
operation() {
return `concreteDecoratorA(${super.operation()})`
}
}
class ConcreteDecoratorB extends Decorator {
operation() {
return `concreteDecoratorB(${super.operation()})`
}
}
const simple = new ConcreteComponent()
const d1 = new ConcreteDecoratorA(simple)

d1.operation()