Wednesday, June 17, 2009

Design Patterns in Javascript: Part 1 Template Method

The Template Method pattern is good for time when you have an algorithm that is pretty stable except at a specific point. So if you have a task defined as :

var worker = {
doTask : function() {
return done;
done : false

So here we have our basic worker. All our workers repeatedly do 3 steps until done to complete task. Let’s define three different types of workers.

First let’s we will need to take care of a deficiency with Javascript prototypal inheritance model:

if (typeof (Object.create) !== 'function'){
Object.create = function (oldObject) {
function F() {}
F.prototype = oldObject;
return new F();

OK, on to the worker objects:

var oneTimer = Object.create(worker);
oneTimer.doStep1 = function() {
// Step 1...
oneTimer.doStep2 = function() {
// Step 2...
oneTimer.doStep3 = function() {
// Step 3...
this.done = true;

var twoTimer = Object.create(oneTimer);
twoTimer.times = 2;
twoTimer.doStep3 = function() {
// Step 3...
this.done = this.times === 0;

var tireless = Object.create(oneTimer);
tireless.doStep3 = function() {
// Infinite worker
this.done = false;

Now I can call the doTask of the worker object that I need. So if I, by some strange occurrence, need a tireless worker I’d do this:


Not much to implement this pattern, is there? This is just like a C# or Java implementation where worker would be and abstract class.

Tuesday, June 16, 2009

Design Patterns in Javascript: Introduction

I have a bit of extra time on my hands right now so I decided to do a series on design patterns in Javascipt. I know some of you have probably heard rumors that Javascript is an object oriented language, right? Well, that is true.
Now some folks used to tell you that Javascript is not object-oriented. They'll probably say something like it's object-based. They'll reason that Javascript doesn't have true inheritance, encapsulation, or polymorphism. What these people really were (and some may still be) saying is that JS does not have class-based object oriented programming, natively. But, classes are not the only way to implement OOP. JS, Lua, and Perl implement OOP using prototypes.

Now since JS is an object-oriented language, we should find at least some of the GOF design patterns useful.

In the next post we will look at the Template Method pattern.