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() {
while(!done){
this.doStep1();
this.doStep2();
this.doStep3();
}
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.times--;
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:


tireless.doTask();


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

No comments: