前端设计模式(三):模板方法模式
2022/6/24 23:24:39
本文主要是介绍前端设计模式(三):模板方法模式,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
模板方法模式的定义:在一个方法里定义算法的骨架,将一些步骤延迟到其子类。
意思是用一个方法包装多个函数的调用,这个方法就是模板,函数的使用只需要跟着模板里的步骤进行即可,同时根据情况可以放入钩子函数来选择是否在指定位置执行函数。
假设我们现在要做饮料,做饮料通常有以下步骤:1、烧开水,2、泡东西,3、倒入杯子,4、加调料
那么用代码描述为:
// ts 定义一个接口 interface IMakeDrinks { /* 烧开水 */ boilWater: () => void; /* 泡东西 */ brew: () => void; /* 倒入杯子 */ pourInCup: () => void; /* 加调料 */ addCondiments: () => void; /* 初始化方法 */ init: () => void }
抽象出来一个父类:
/** * 做饮料父类 */ class AbstractMakeDrinks implements IMakeDrinks{ isAddCondiments: boolean = false; constructor(isAddCondiments: boolean) { this.isAddCondiments = isAddCondiments; } addCondiments() { throw new Error('需要子类实现') } boilWater() { throw new Error('需要子类实现') } brew() { throw new Error('需要子类实现') } pourInCup() { throw new Error('需要子类实现') } init() { this.boilWater(); this.brew(); this.pourInCup(); if(this.isAddCondiments){ this.addCondiments(); } } }
具体子类来实现做东西的过程,然后调用父类的init方法搞定
class Coffee extends AbstractMakeDrinks { boilWater() { console.log('把白开水烧开') } brew() { console.log('把咖啡和水导入壶里') } pourInCup() { console.log('倒入咖啡杯') } addCondiments() { console.log('加牛奶和糖') } } const coffee = new Coffee(true); coffee.init();
假设有牛奶饮品,一样的套路。
当做饮料的种类多了,并结合策略模式:
// 结合策略模式 const getDrinks = (type: string) => { const typeStrategy: any = { 'coffee': new Coffee(true) } return typeStrategy[type] } const drinkObj = getDrinks('coffee'); drinkObj.init();
这篇关于前端设计模式(三):模板方法模式的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-09一定要避坑:关于微信H5分享,温馨提示你不要再踩坑了!!!
- 2024-05-09本地项目放到公网访问!炒鸡煎蛋!
- 2024-04-07金融企业区域集中库的设计构想和测试验证
- 2024-03-11前端CSS的工程化——掌握Sass这四大特性就够了
- 2024-02-21h5关联css样式(html怎么和css关联)-icode9专业技术文章分享
- 2024-02-07Firefox禁止远程字体加速网页加载及图标字体补充安装
- 2024-02-07一个菜鸡前端的3年总结-「2023」
- 2024-01-18最火前端Web组态软件(可视化)
- 2024-01-12程序员提效 x10 的必备开源“神器”
- 2024-01-11前端可以监控静态资源的时间吗-icode9专业技术文章分享