为类添加功能,但不会修改这个类。
    继承基本可以实现,也是最简单,但是类只能继承一个父类。如果要增加多个功能时,继承就不那么适合。
    这时装饰器就发挥作用。

    1. class Shape {}
    2. class Circle extends Shape {
    3. constructor(radius = 0){
    4. super();
    5. this.radius = radius;
    6. }
    7. resize(factor){
    8. this.radius *= factor;
    9. }
    10. toString(){
    11. return `一个半径为 ${this.radius} 的圆形`;
    12. }
    13. }

    装饰器

    1. class ColoredShape extends Shape {
    2. constructor(shape, color){
    3. super();
    4. this.shape = shape;
    5. this.color = color;
    6. }
    7. toString(){
    8. return `${this.shape.toString()} 它有着 ${this.color} 的颜色`;
    9. }
    10. }
    11. class TransparentShape extends Shape {
    12. constructor(shape, transparency){
    13. super();
    14. this.shape = shape;
    15. this.transparency = transparency;
    16. }
    17. toString(){
    18. return `${this.shape.toString()} 它有着 ${this.transparency * 100}% 的透明度`;
    19. }
    20. }
    21. let circle = new Circle(2);
    22. let redCircle = new ColoredShape(circle, 'red');
    23. redCircle.shape.resize(5);
    24. console.log(redCircle.toString());
    25. let redHalfCircle = new TransparentShape(redCircle, 0.5);
    26. redHalfCircle.shape.shape.resize(10);
    27. console.log(redHalfCircle.toString());

    调用 cirle 的 resize 时要多走几层。