装饰器模式
在不改变其原有的结构和功能为对象添加新功能,装饰比继承更加灵活。
就像你有一把狙击枪它需要消音的功能,我们就可以装上一个消音器。要一个四倍镜就可以
装上四倍镜,然后是握把,枪架等等。可以把消音器、四倍镜、握把、枪架…相当于装饰器概念。
// 狙击枪
class SniperRifle {
// 枪配置
configuration() {
return `狙击枪体`
}
// 枪的综合战力
fightingCapacity() {
return 2000
}
};
// 消音器
class Silencer {
constructor(parent) {
this.parent = parent;
}
// 枪配置
configuration() {
return `${this.parent.configuration()}+消音器`
}
// 枪的综合战力
fightingCapacity() {
return this.parent.fightingCapacity() + 100
}
};
// 四倍镜
class Telescope {
constructor(parent) {
this.parent = parent;
}
// 枪配置
configuration() {
return `${this.parent.configuration()}+四倍镜`
}
// 枪的综合战力
fightingCapacity() {
return this.parent.fightingCapacity() + 120
}
}
// ...
// 这可以扩展很多装饰器
// 要一把狙击枪
let sniperRifle1 = new SniperRifle();
console.log(sniperRifle1.configuration())
console.log(sniperRifle1.fightingCapacity())
// 要一把有消音器的狙击枪
let sniperRifle2 = new Silencer(new SniperRifle)
console.log(sniperRifle2.configuration())
console.log(sniperRifle2.fightingCapacity())
// 要一把有消音器加四倍的狙击枪
let sniperRifle3 = new Telescope(new Silencer(new SniperRifle))
console.log(sniperRifle3.configuration())
console.log(sniperRifle3.fightingCapacity())
这样可以在原有的功能上添加功能而不用修改原来的代码了,自由灵活性就很高。