1. 程式人生 > >ES6設計模式之模版方法模式

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