Search code examples
design-patternsdecoratordecorator-chaining

Does it matter when a decorator gets called (at the beginning or at the end of the method) in the decorator pattern?


I'm implementing a decorator pattern in Javascript.

I've seen the example here in Wikipedia

// Class to be decorated
function Coffee() {
    this.cost = function() {
    return 1;
    };
}

// Decorator A
function Milk(coffee) {
    this.cost = function() {
    return coffee.cost() + 0.5;
    };  
}

// Decorator B
function Whip(coffee) {
    this.cost = function() {
    return coffee.cost() + 0.7;
    };
}

// Decorator C
function Sprinkles(coffee) {
    this.cost = function() {
    return coffee.cost() + 0.2;
    };
}

// Here's one way of using it
var coffee = new Milk(new Whip(new Sprinkles(new Coffee())));
alert( coffee.cost() );

// Here's another
var coffee = new Coffee();
coffee = new Sprinkles(coffee);
coffee = new Whip(coffee);
coffee = new Milk(coffee);
alert(coffee.cost());

Now my question is for the pattern to still be a decorator pattern, does it matter if the parent class is called at the beginning or the end of the cost() function?

Now granted I realize that this depends on what each of the decorators do...for instance if your are multiplying or dividing in your decorator instead of adding or subtracting, it will of course warrant a different result.

But is there any reason to make the call before or after other than the reason I stated in the previous paragraph?


Solution

  • Okay found the answer.

    I went back and re-read the Decorator Pattern part of my design patterns book and found:

    "The decorator adds its own behavior either before and/or after delegating to the object it decorates to do the rest of the job."

    With the emphasis being on the before and/or after bit...

    Sorry to have bothered you and thanks for the answers.