JavaScript template method pattern

1. The template method pattern: a very simple pattern that can be achieved only by using inheritance.

2. The template method pattern consists of two parts, the first part is the abstract parent class, and the second part is the concrete implementation subclass.

3. Use Coffee or Tea in the design pattern to illustrate the template method pattern:

1. The template Brverage, the code is as follows:

var Beverage = function(){};
Beverage.prototype.boilWater = function(){
   console.log('把水煮沸');
};
Beverage.prototype.pourInCup = function(){
    throw new Error( '子类必须重写pourInCup' );
};
Beverage.prototype.addCondiments = function(){
   throw new Error( '子类必须重写addCondiments方法' );
};
Beverage.prototype.customerWantsConditions = function(){
   return true; //默认需要调料
};
Beverage.prototype.init = function(){
   this.boilWater();
   this.brew();
   this.pourInCup();
   if(this.customerWantsCondiments()){
       //如果挂钩返回true,则需要调料
       this.addCondiments();
   }
};

2. The child class inherits the parent class

var CoffeeWithHook = function(){};
CoffeeWithHook.prototype = new Beverage();
CoffeeWithHook.prototype.brew = function(){
   console.log('把咖啡倒进杯子');
};
CoffeeWithHook.prototype.addCondiments = function(){
   console.log('加糖和牛奶');
};
CoffeeWithHook.prototype.customerWantsCondiments = function(){
  return window.confirm( '请问需要调料吗?' );
};

3. Make a cup of coffee

var coffeeWithHook = new CoffeeWithHook();
coffeeWithHook.init();

Four, another way of writing

var Beverage = function( param ){
   var boilWater = function(){
      console.log( '把水煮沸' );
   };
   
   var brew = param.brew || function(){
      throw new Error( '必须传递brew方法' );
   };

   var pourInCup = param.pourInCup || function(){
       throw new Error( '必须传递pourInCup方法' );
   };

   var addCondiments = param.addCondiments || function(){
      throw new Error( '必须传递addCondiments方法' );
   };

   var F = function(){};

   F.prototype.init = function(){
     boilWater();
     brew();
     pourInCup();
     addCondiments();
   };

   return F;
};

var Coffee = Beverage({
   brew: function(){
         console.log( '用沸水冲泡咖啡' );
   },
   pourInCup: function(){
       console.log('把咖啡倒进杯子');
   },
   addCondiments: function(){
       console.log('加糖和牛奶');
   }
});

var coffee = new Coffee();
coffee.init();

Guess you like

Origin blog.csdn.net/joyksk/article/details/79853344