JavaScript设计模式之模板方法模式原理与用法示例

每一天的生活,不再为一点小事悲痛动怒,会安安心心,简简单单,做一些能让自己开心的事。不要过分在意一些人,过分在乎一些事,顺其自然,以最佳的心态应对。

本文实例讲述了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();

上述代码使用在线HTML/CSS/JavaScript代码运行工具http://tools.haodaima.com/code/HtmlJsRun测试运行结果:

希望本文所述对大家JavaScript程序设计有所帮助。

本文JavaScript设计模式之模板方法模式原理与用法示例到此结束。船的命运在于漂泊;帆的命运在于追风逐浪;人生的命运在于把握,把握信人生,方能青春无愧。小编再次感谢大家支持!

您可能有感兴趣的文章
javascript请求servlet实现ajax示例(分享)

JavaScript操作表单_动力节点Java学院整理

纯javascript的ajax实现php异步提交表单的简单实例

JavaScript实现Ajax总结

初步了解JavaScript,Ajax,jQuery,并比较三者关系