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

本文实例讲述了JavaScript设计模式之模板方法模式原理与用法。分享给大家供大家参考,具体如下:

成都创新互联公司坚信:善待客户,将会成为终身客户。我们能坚持多年,是因为我们一直可值得信赖。我们从不忽悠初访客户,我们用心做好本职工作,不忘初心,方得始终。十多年网站建设经验成都创新互联公司是成都老牌网站营销服务商,为您提供成都网站设计、成都网站建设、网站设计、H5响应式网站、网站制作、品牌网站设计小程序开发服务,给众多知名企业提供过好品质的建站服务。

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

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

三、以设计模式中的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.jb51.net/code/HtmlJsRun测试运行结果:

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

更多关于JavaScript相关内容可查看本站专题:《javascript面向对象入门教程》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》

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

网站题目:JavaScript设计模式之模板方法模式原理与用法示例
分享URL:https://www.cdcxhl.com/article2/gijpic.html

成都网站建设公司_创新互联,为您提供微信小程序品牌网站制作静态网站网站导航标签优化品牌网站建设

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

搜索引擎优化