为类添加功能,但不会修改这个类。
继承基本可以实现,也是最简单,但是类只能继承一个父类。如果要增加多个功能时,继承就不那么适合。
这时装饰器就发挥作用。
class Shape {}
class Circle extends Shape {
constructor(radius = 0){
super();
this.radius = radius;
}
resize(factor){
this.radius *= factor;
}
toString(){
return `一个半径为 ${this.radius} 的圆形`;
}
}
装饰器
class ColoredShape extends Shape {
constructor(shape, color){
super();
this.shape = shape;
this.color = color;
}
toString(){
return `${this.shape.toString()} 它有着 ${this.color} 的颜色`;
}
}
class TransparentShape extends Shape {
constructor(shape, transparency){
super();
this.shape = shape;
this.transparency = transparency;
}
toString(){
return `${this.shape.toString()} 它有着 ${this.transparency * 100}% 的透明度`;
}
}
let circle = new Circle(2);
let redCircle = new ColoredShape(circle, 'red');
redCircle.shape.resize(5);
console.log(redCircle.toString());
let redHalfCircle = new TransparentShape(redCircle, 0.5);
redHalfCircle.shape.shape.resize(10);
console.log(redHalfCircle.toString());
调用 cirle 的 resize 时要多走几层。