JavaScriptによるテンプレートパターン実装

テンプレートパターンをJavaScriptで実装してみた。結構簡単。
以下を実行すると、child2.execute() が呼び出されて、before, child2!, after の順に表示される。

<html>
<head>
<script>
var Parent = function(){
	return {
		before: null,
		after: null,
		_execute: null,
		execute: function(){
			if( this.before != null ) this.before();
			this._execute();
			if( this.after != null ) this.after();
		}
	}
}

var Child = function(){
	var parent = Parent();

	parent._execute = function(){
		alert('exec' );
	}

	parent.before = function(){
		alert('before');
	}

	parent.after = function(){
		alert('after');
	}

	return parent;
}

var Child2 = function(){
	var child = Child();
	child._execute = function(){
		alert('child2!');
	}
	return child;
}

var child2 = Child2();
child2.execute();

</script>
</head>
</html>