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

猜你喜欢

转载自www.cnblogs.com/node-jili/p/10161507.html