本篇文章给大家带来的内容是关于js设计模式:什么是模板方法模式?js模板方法模式的介绍,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
什么是模板方法模式?定义:定义一个操作中的算法的骨架,而将一些步骤延迟到子类中。模板方法使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
主要解决:一些方法通用,却在每一个子类都重新写了这一方法。
何时使用:有一些通用的方法。
如何解决:将这些通用算法抽象出来。
js模板方法模式应用实例: 1、在造房子的时候,地基、走线、水管都一样,只有在建筑的后期才有加壁橱加栅栏等差异。 2、西游记里面菩萨定好的 81 难,这就是一个顶层的逻辑骨架。
js模板方法模式优点: 1、封装不变部分,扩展可变部分。 2、提取公共代码,便于维护。 3、行为由父类控制,子类实现。
js模板方法模式缺点:每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。
js模板方法模式使用场景: 1、有多个子类共有的方法,且逻辑相同。 2、重要的、复杂的方法,可以考虑作为模板方法。
泡茶和泡咖啡来对比下泡茶和泡咖啡过程中的异同
步骤泡茶泡咖啡
1 烧开水 烧开水
2 浸泡茶叶 冲泡咖啡
3 倒入杯子 倒入杯子
4 加柠檬 加糖
可以清晰地看出仅仅在步骤 2 和 4 上有细微的差别,下面着手实现:
const drinks = function() {}drinks.prototype.firststep = function() { console.log('烧开水')}drinks.prototype.secondstep = function() {}drinks.prototype.thirdstep = function() { console.log('倒入杯子')}drinks.prototype.fourthstep = function() {}drinks.prototype.init = function() { // 模板方法模式核心:在父类上定义好执行算法 this.firststep() this.secondstep() this.thirdstep() this.fourthstep()}const tea = function() {}tea.prototype = new drinkstea.prototype.secondstep = function() { console.log('浸泡茶叶')}tea.prototype.fourthstep = function() { console.log('加柠檬')}const coffee = function() {}coffee.prototype = new drinkscoffee.prototype.secondstep = function() { console.log('冲泡咖啡')}coffee.prototype.fourthstep = function() { console.log('加糖')}const tea = new tea()tea.init()// 烧开水// 浸泡茶叶// 倒入杯子// 加柠檬const coffee = new coffee()coffee.init()// 烧开水// 冲泡咖啡// 倒入杯子// 加糖
钩子假如客人不想加佐料(糖、柠檬)怎么办,这时可以引人钩子来实现之,实现逻辑如下:
// ...drinks.prototype.ifneedflavour = function() { // 加上钩子 return true}drinks.prototype.init = function() { // 模板方法模式核心:在父类上定义好执行算法 this.firststep() this.secondstep() this.thirdstep() if (this.ifneedflavour()) { // 默认是 true,也就是要加调料 this.fourthstep() }}// ...const coffee = function() {}coffee.prototype = new drinks()// ...coffee.prototype.ifneedflavour = function() { return window.confirm('是否需要佐料吗?') // 弹框选择是否佐料}
相关推荐:
js设计模式: 什么是组合模式?js组合模式的介绍
js设计模式:什么是观察者模式(发布订阅模式)?js观察者模式的介绍
以上就是js设计模式:什么是模板方法模式?js模板方法模式的介绍的详细内容。