天天看点

JavaScript装饰者模式装饰者模式的结构装饰者模式与组合模式的比较装饰者修改其组件的方式

装饰者可以透明地把对象包装在具有同样接口的另一对象中。

装饰者模式的结构

装饰者可用于为对象增加功能,可以替代大量子类。

function Bicycle() {

    }
    Bicycle.prototype.getPrice = function (){
        return 399;
    }

    // 继承函数
    function extend(subClass, supClass){
        function F(){}
        F.prototype = supClass.prototype;
        subClass.prototype = new F();
        subClass.prototype.constructor = subClass;
        subClass.superclass = supClass.prototype;
    }

    // 装饰者父类
    function Decorator(bicycle) {
        this.bicycle = bicycle;
    }
    Decorator.prototype.getPrice = function() {
        return this.bicycle.getPrice();
    }

    // HeadLightDecorator装饰类
    function HeadLightDecorator(bicycle) {
        HeadLightDecorator.superclass.constructor.call(this, bicycle);
    }
    extend(HeadLightDecorator, Decorator);
    HeadLightDecorator.prototype.getPrice = function () {
        return this.bicycle.getPrice() + 15;
    }
    

    // TaillightDecorator装饰类
    function TaillightDecorator(bicycle) {
        TaillightDecorator.superclass.constructor.call(this, bicycle);
    }
    extend(TaillightDecorator, Decorator);
    TaillightDecorator.prototype.getPrice = function ()  {
        return this.bicycle.getPrice() + 20;
    }
   

    let myBicycle = new Bicycle();
    console.log(myBicycle.getPrice());
    

    myBicycle = new HeadLightDecorator(myBicycle);
    console.log(myBicycle.getPrice());

    myBicycle = new TaillightDecorator(myBicycle);
    console.log(myBicycle.getPrice());
           

装饰者模式与组合模式的比较

相同点:

  • 装饰者和组合模式都是用来包装别的对象,它们都与所包装的对象拥有同样的方法,并且会把这些方法的调用传递给被包装的对象。
  • 都是结构型模式

不同点

  • 组合模式用于把众多子对象组织成一个整体。
  • 装饰者不用于组织对象,而是用于在不修改现有对象,或从其派生子类的前提下为其增添职责。

装饰者修改其组件的方式

  1. 在方法之后添加行为
  2. 在方法之前添加行为
  3. 替换方法
  4. 添加新方法

继续阅读