JavaScript模板方法模式

一、模板方法模式:一种只需使用继承就可以实现的非常简单的模式。

二、模板方法模式由两部分组成,第一部分是抽象父类,第二部分是具体的实现子类。

三、以设计模式中的Coffee or Tea来说明模板方法模式:

1、模板Brverage,代码如下:

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、子类继承父类

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、煮一杯咖啡

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

四、另一种写法

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();

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值