Prototype based languages offer a different way of implementing objects, and hence require a different thinking for structuring your programs. They make you think more in terms of messages that your objects will receive, and how the messages get propagated up the inheritance chain.
Javascript follows an almost identical architecture, where the hierarchies of objects are constructed through prototypes. This post is not about Self or, for that matter, about the Javascript language. Some time back I had blogged about how the Template Method design pattern gets subsumed into higher order functions and closures when implemented using functional programming languages.
In a class based language, template method pattern is implemented in terms of inheritance, which makes the structure of the pattern static and makes the derivatives of the hierarchy statically coupled to the base abstraction. Closures liberate the pattern structure from this compile time coupling and make it dynamic. But once we take off the class inheritance part and use higher order functions to plug in the variable parts of the algorithm, what we end up with closely matches the Strategy pattern. Have a look at James Iry's insightful comments in my earlier post.
James also hinted at another level of subsumption which is more interesting - the case of the two patterns implemented in a prototype based language like Javascript. Here is how it looks ..
// the template function at the base object
// defines the generic flow
// uses hooks to be plugged in by derived objects
var processor = {
process: function() {
this.doInit();
this.doProcess();
this.doEnd();
return true;
}
};
We construct another object that inherits from the base object. The function
beget
is the one that Douglas Crockford defines as a helper to create a new object using another object as the prototype.if (typeof Object.beget !== 'function') {
Object.beget = function(o) {
var F = function() {};
F.prototype = o;
return new F();
};
}
var my_processor = Object.beget(processor);
The new object now implements the variable parts of the algorithm.
my_processor.doInit = function() {
//..
};
my_processor.doProcess = function() {
//..
};
my_processor.doEnd = function() {
//..
};
and we invoke the function from the base object ..
my_processor.process();
If we need to define another specialization of the algorithm that only has to override a single variable part, we do it likewise by supplying the object my_processor as the prototype ..
var your_processor= Object.beget(my_processor);
your_processor.doEnd = function() {
//.. another specialization
};
your_processor.process();
So what we get is a dynamic version of the Template Method pattern with no static coupling - thanks to prototypal inheritance of Javascript. Is this a Template Method pattern or a Strategy pattern ? Both get subsumed into the prototypal nature of the language.