您现在的位置是:首页 > 文章详情

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

日期:2019-04-11点击:405

什么是模板模式?

模板模式是抽象父类定义了子类需要重写的相关方法。 而这些方法,仍然是通过父类方法调用的。 根据描述,“模板”的思想体现在:父类定义的接口方法。 除此之外,子类方法的调用,也是被父类控制的。

应用场景

一些系统的架构或者算法骨架,由“BOSS”编写抽象方法,具体的实现,交给“小弟们”实现。 而绝对是不是用“小弟们”的方法,还是看“BOSS”的心情。 不是很恰当的比喻哈~

ES6 实现

Animal是抽象类,Dog和Cat分别具体实现了eat()和sleep()方法。 Dog或Cat实例可以通过live()方法调用eat()和sleep()。

注意:Cat和Dog实例会被自动添加live()方法。不暴露live()是为了防止live()被子类重写,保证父类的控制权。

class Animal {
constructor() {

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

}

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指向cat
let cat = new Cat();
cat.live();
好程序员web前端分享

原文链接:https://yq.aliyun.com/articles/697906
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章