好程序員web前端教程分享js模板模式

什麼是模板模式?算法

模板模式是抽象父類定義了子類須要重寫的相關方法。 而這些方法,仍然是經過父類方法調用的。 根據描述,「模板」的思想體如今:父類定義的接口方法。 除此以外,子類方法的調用,也是被父類控制的。 架構

應用場景測試

一些系統的架構或者算法骨架,由「BOSS」編寫抽象方法,具體的實現,交給「小弟們」實現。 而絕對是否是用「小弟們」的方法,仍是看「BOSS」的心情。 不是很恰當的比喻哈~this

ES6 實現code

Animal是抽象類,Dog和Cat分別具體實現了eat()和sleep()方法。 Dog或Cat實例能夠經過live()方法調用eat()和sleep()。 接口

注意:Cat和Dog實例會被自動添加live()方法。不暴露live()是爲了防止live()被子類重寫,保證父類的控制權。console

class Animal {
constructor() {模板

// this 指向實例
this.live = () => {
  this.eat();
  this.sleep();
};

}class

eat() {方法

throw new Error("模板類方法必須被重寫");

}

sleep() {

throw new Error("模板類方法必須被重寫");

}
}

class Dog extends Animal {
constructor(...args) {

super(...args);

}
eat() {

console.log("狗吃糧");

}
sleep() {

console.log("狗睡覺");

}
}

class Cat extends Animal {
constructor(...args) {

super(...args);

}
eat() {

console.log("貓吃糧");

}
sleep() {

console.log("貓睡覺");

}
}

/ 如下爲測試代碼 */

// 此時, Animal中的this指向dog
let dog = new Dog();
dog.live();

// 此時, Animal中的this指向catlet cat = new Cat();cat.live();

相關文章
相關標籤/搜索