1. Template Method mode 1.1 object-oriented implementation of template method pattern
Take tea and coffee for example, can be organized into the following four steps
- Boil the water
- Brew a drink in boiling water
- Pour the drink into the cup
- Add seasoning
First, create an abstract parent class to represent a drink.
varBeverage=function(){}; Beverage.prototype.boilWater=function() {Console.log (' Boil the water ');}; Beverage.prototype.brew=function(){};//empty method, overridden by subclassesbeverage.prototype.pourincup=function(){};//empty method, overridden by subclassesbeverage.prototype.addcondiments=function(){};//empty method, overridden by subclassesbeverage.prototype.init=function(){ This. Boilwater (); This. Brew (); This. Pourincup (); This. addcondiments ();};
Next, create the coffee subclass and tea sub-class
var coffee=function() {}; Coffee.prototype=new beverage ();
Overriding the abstract method of the parent class
coffee.prototype.brew=function() { console.log (' brew coffee with boiling water ');}; Coffee.prototype.pourInCup=function() { console.log (' Pour the coffee into the cup '); Coffee.prototype.addCondiments=function() { Console.log (' Add sugar and milk ');}; var coffee=New Coffee (); Coffee.init ();
Continue to create tea class
var tea=function() {}; Tea.prototype=new beverage (); Tea.prototype.brew=function() { console.log (' soak tea with boiling water ');}; Tea.prototype.pourInCup=function() { console.log (' Pour the tea into the cup '); Tea.prototype.addCondiments=function() { console.log (' plus lemon ');}; var tea=New tea (); Tea.init ();
In the above example,Beverage.prototype.init is a template method that encapsulates the algorithm framework for subclasses
It serves as a template for an algorithm that instructs the subclass in what order to execute which methods
1.2 Template method Patterns in JavaScript
varBeverage=function(param) {varBoilwater=function() {Console.log (' Boil the water '); }; varbrew=param.brew| |function(){ Throw NewError (' must pass the Brew method '); }; varpourincup=param.pourincup| |function(){ Throw NewError (' must pass Pourincup method ')); }; varaddcondiments=param.addcondiments| |function(){ Throw NewError (' must pass Addcondiments method ')); }; varf=function(){}; F.prototype.init=function() {boilwater (); Brew (); Pourincup (); Addcondiments (); }; returnF;};varCoffee=Beverage ({brew:function() {Console.log (' Brew coffee with boiling water '); }, Pourincup:function() {Console.log (' Pour the coffee into the cup '); }, Addcondiments:function() {Console.log (' Add sugar and milk '); } });varTea=Beverage ({brew:function() {Console.log (' Soak tea with boiling water '); }, Pourincup:function() {Console.log (' Pour the tea into the cup '); }, Addcondiments:function() {Console.log (' Add lemon '); } });varCoffee=NewCoffee (); Coffee.init ();varTea=NewTea (); Tea.init ();
"JavaScript design pattern and Development practice" the template method pattern of reading notes