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.

3 comments:

Gabe Co Hadwin said...

Design Patterns in Javascript:

Gabe Co Hadwin said...

The Template Method pattern is a useful way to structure JavaScript code when the overall workflow remains consistent while individual steps may vary between implementations. The example of repeatedly executing doStep1(), doStep2(), and doStep3() makes the idea of separating the fixed algorithm from customizable behavior easy to understand.

What I particularly found useful is the focus on JavaScript's prototypal inheritance model, since implementing a classical design pattern in JavaScript often requires adapting the pattern to the language rather than copying an implementation from class-based languages. For developers learning Javascript Online Training, this is a good example of how design patterns can be connected to practical language features rather than treated only as theoretical concepts.

Gabe Co Hadwin said...

The approach also demonstrates why reusable algorithm structures can make variations between different workers easier to manage without duplicating the entire workflow. For someone studying Javascript Online Course, understanding this distinction between the invariant part of an algorithm and the parts intended for specialization is valuable when designing maintainable JavaScript applications.