天天看點

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. 添加新方法

繼續閱讀