Agile Zone is brought to you in partnership with:

I am a programmer and architect (the kind that writes code) with a focus on testing and open source; I maintain the PHPUnit_Selenium project. I believe programming is one of the hardest and most beautiful jobs in the world. Giorgio is a DZone MVB and is not an employee of DZone and has posted 635 posts at DZone. You can read more from them at their website. View Full User Profile

The Decorator pattern, or its cousin, in JavaScript

02.09.2012
| 4360 views |
  • submit to reddit
The Decorator pattern is a way to reduce multiple levels of inheritance that clash with each other; for example, if you want to create objects which address one or more between the X, Y or Z responsibilities, plain inheritance leads you to create the following classes:
BaseClass
X
Y
Z
XY
XZ
YZ
XYZ
while the Decorator pattern allows you to create just:
BaseClass
XDecorator
YDecorator
ZDecorator
The variation of the Decorator pattern we'll see implemented in JavaScript does not respect a fundamental tenet of the original one: the decorated objects expand the interface of BaseClass. Feel free to comment if you recognized a more familiar pattern in the code instead of Decorator; the focus here is in:
  • automatically inherit methods from the decorated object.
  • Being able to override methods of the decorated objects to introduce new behavior.
  • Being able to call methods of the decorated objects during an override, liek would you do with super() in Java or parent:: in PHP.

The initial state

We start from the base class, Ball. The name of the classes and methods are totally naive, as they are here to shown us how to link together objects in JavaScript more than model a real design.

The tests are written with jsTestDriver, which conforms to xUnit. Since JavaScript does not support classes, we are using constructor functions; moreover, I'm ignoring sharing of functions between instances of the same class for simplicity.

TestCase("basic Ball object test", {
    "test it should tell us what it is" : function() {
         var ball = new Ball();
         assertEquals("I am a ball", ball.what());
    }
});
function Ball() {
    this.what = function() {
        return "I am a ball";
    }
}

Now we have two different characteristics we want to add to Ball objects, zero or more at a time:
 

    "test a blinking ball is a ball that can blink" : function () {
         var ball = new BlinkingBall();
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canBlink());
    },
    "test a jumping ball is a ball that can jump" : function () {
         var ball = new JumpingBall();
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canJump());
    },
    "test a blinking&jumping ball is a ball that can do both" : function () {
         var ball = new BlinkingJumpingBall();
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canBlink());
         assertTrue(ball.canJump());
    }

You can see how this design forces you to introduce 2^N (in this case 2^2) classes.

Decorating

Let's specify a design based on Decorators instead. The object we create initially is always a Ball; afterwards, it is wrapped at runtime with one or more strata. Each stratum is a new object, a level of indirection where new behavior can be put and method calls can be intercepted.

TestCase("basic Ball object test", {
    "test it should tell us what it is" : function() {
         var ball = new Ball();
         assertEquals("I am a ball", ball.what());
    },
    "test a blinking ball is a ball that can blink" : function () {
         var ball = Blinking.decorate(new Ball());
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canBlink());
    },
    "test a jumping ball is a ball that can jump" : function () {
         var ball = Jumping.decorate(new Ball());
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canJump());
    },
    "test a blinking&jumping ball is a ball that can do both" : function () {
         var ball = Blinking.decorate(Jumping.decorate(new Ball()));
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canBlink());
         assertTrue(ball.canJump());
    }
});

Since decoration is performed at runtime, you don't have to create a BlinkingJumping decorator, but just chain the existing decorators together on creation of the Ball object (or you can decorate it long after creation.)

This is the full implementation of the Ball class and its two Decorators:

function Ball() {
    this.what = function() {
        return "I am a ball";
    }
}

Blinking = {};
Blinking.decorate = function(originalBall) {
    newBallConstructor = function() {
        this.canBlink = function() {
            return true;
        };
    };
    newBallConstructor.prototype = originalBall;
    return new newBallConstructor();
}

Jumping = {};
Jumping.decorate = function(originalBall) {
    newBallConstructor = function() {
        this.canJump = function() {
            return true;
        };
    };
    newBallConstructor.prototype = originalBall;
    return new newBallConstructor();
}

The constructor function newBallConstructor is created on the fly during each decoration; it adds to this (the object which will be created) new methods. Moreover, the prototype of this function is linked to the original object; the effect is that method calls not defined by newBallConstructor are delegated by the interpreted to originalBall.
Since the decorator creation code is fairly standard, we can eliminate duplication by extracting it:

createDecorator = function(newConstructor) {
    return function(originalObject) {
        newConstructor.prototype = originalObject;
        return new newConstructor();
    };
};

Blinking = {};
Blinking.decorate = createDecorator(function() {
    this.canBlink = function() {
        return true;
    };
});
 

The standard

The standard Decorator pattern, however, is based on intercepting calls more than on expanding the interface of the object with new methods; this semantics is also due to the statically typed languages it is implemented in, which won't allow a dynamic interface where the caller does not know which methods are available at compile time.

We can decorate an existing method too. Let's change the tests to:

TestCase("basic Ball object test", {
    "test it should tell us what it is" : function() {
         var ball = new Ball();
         assertEquals("I am a ball", ball.what());
    },
    "test a blinking ball is a ball that can blink" : function () {
         var ball = Blinking.decorate(new Ball());
         assertEquals("I am a ball (and I can blink)", ball.what());
         assertTrue(ball.canBlink());
    },
    "test a jumping ball is a ball that can jump" : function () {
         var ball = Jumping.decorate(new Ball());
         assertEquals("I am a ball", ball.what());
         assertTrue(ball.canJump());
    },
    "test a blinking&jumping ball is a ball that can do both" : function () {
         var ball = Blinking.decorate(Jumping.decorate(new Ball()));
         assertEquals("I am a ball (and I can blink)", ball.what());
         assertTrue(ball.canBlink());
         assertTrue(ball.canJump());
    }
});

Now the Blinking Decorator should call the original Ball.what() method, and concatenate " (and I can blink)" to the result before returning.

Blinking.decorate = createDecorator(function() {
    oldWhat = this.what;
    this.what = function() {
        return oldWhat.apply(this) + " (and I can blink)";
    }
    this.canBlink = function() {
        return true;
    };
});

Inside a constructor function, this always binds to the object under creation, even inside functions. So we perform these steps:

  1. saving oldWhat before overwriting it; since the object to decorate is assigned to the prototype, we can do so just by accessing a field on this.
  2. Defining a brand new this.what, which will have priority over the prototype methods.
  3. Delegating part of the method to the original one, by calling apply() on the Function object oldWhat. apply() ensures this inside oldWhat() is bind to the current object.
Published at DZone with permission of Giorgio Sironi, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)