>[success] # 钩子方法 ~~~ 1.钩子方法(hook)放置钩子是隔离变化的一种常见手段,在父 类中容易变化的地方 放置钩子,钩子可以有一个默认的实现,究竟要不要'挂钩',这由子类自 行决定。 2.钩子方法的返回结果决定了模板方法后面部分的执行步骤,也就是程序接下来的走向, 这样一来,程序就拥有了变化的可能。 ~~~ >[danger] ##### 书中的案例 ~~~ 1.书中定义了一个'customerWantsCondiments' 钩子来决定咖啡是否需要要糖和牛奶,来决定 整个程序的走向 ~~~ ~~~ var Beverage = function(){}; Beverage.prototype.boilWater = function(){ console.log( '把水煮沸' ); }; Beverage.prototype.brew = function(){ throw new Error( '子类必须重写 brew 方法' ); }; Beverage.prototype.pourInCup = function(){ throw new Error( '子类必须重写 pourInCup 方法' ); }; Beverage.prototype.addCondiments = function(){ throw new Error( '子类必须重写 addCondiments 方法' ); }; Beverage.prototype.customerWantsCondiments = function(){ return true; // 默认需要调料 }; Beverage.prototype.init = function(){ this.boilWater(); this.brew(); this.pourInCup(); if ( this.customerWantsCondiments() ){ // 如果挂钩返回 true,则需要调料 this.addCondiments(); } }; var CoffeeWithHook = function(){}; CoffeeWithHook.prototype = new Beverage(); CoffeeWithHook.prototype.brew = function(){ console.log( '用沸水冲泡咖啡' ); }; CoffeeWithHook.prototype.pourInCup = function(){ console.log( '把咖啡倒进杯子' ); }; CoffeeWithHook.prototype.addCondiments = function(){ console.log( '加糖和牛奶' ); }; CoffeeWithHook.prototype.customerWantsCondiments = function(){ return window.confirm( '请问需要调料吗?' ); }; var coffeeWithHook = new Coff } ~~~