ES6设计模式之模版方法模式

这是一个常用的模式,也是一个容易理解的模式,我从这里面认识了什么叫钩子方法。 模版方法模式,很简单就是就是父类中对算法进行封装,子类中添加子集的方法做不同实现,并且父类中可以设置钩子函数,子类通过调用钩子函数控制父类的算法流程。注意这里还有一个原则,避免对象之间过度依赖。会造成项目混乱,要遵循最少知识原则。代码如下: const fs = require(‘fs’);

function readSyncByfs(tips) { tips = tips || '> '; process.stdout.write(tips); process.stdin.pause(); const buf = Buffer.allocUnsafe(10000); var response = fs.readSync(process.stdin.fd, buf, 0, 10000, 0); process.stdin.end(); return buf.toString(‘utf8’, 0, response).trim(); } class Drinks { constructor(name){ this.condiment = name; }

addwater(){ console.log(“add water!”); }

static brew(){ throw “you should make this one clearly.”; }

pourInCup(){ console.log(“pour in cup!”); }

static addCondiments(){ throw “diffents drinks with diffents condiments”; }

condimentsHook(){ // TODO: Log the answer in a database var args = readSyncByfs(do you want to put ${this.condiment} in drinks.); if(args == “yes”) { this.addCondiments(); }else{ console.log(“have done nothing!”); } }

makeDrinks(){ this.addwater(); this.brew(); this.pourInCup(); this.condimentsHook() }

} // 注意静态方法必须有子类实现

class Tea extends Drinks{ constructor(){ super(‘lemon’); }

brew(){ console.log(“Boil the water.”); }

addCondiments(){ console.log(“Add lemon”); } }

class Coffe extends Drinks{ constructor(){ super(‘sugar and milk’); }

brew(){ console.log(“Brewing in boiling water.”); }

addCondiments(){ console.log(“Add sugar and milk”); } }

let myTea = new Tea(); myTea.makeDrinks(); let myCoffe = new Coffe(); myCoffe.makeDrinks();

转载于:https://www.cnblogs.com/node-jili/p/10161507.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值