【十月打卡】第70天 前端常用的7种设计模式(6)
2022/10/27 4:25:00
本文主要是介绍【十月打卡】第70天 前端常用的7种设计模式(6),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
工厂模式
概念
工厂模式把创建对象或者实例的方法进行统一封装处理,不再需要每次自己创建。
一般遇到new class的场景,可以尝试考虑使用工厂模式。
代码演示和UML类图
- 符合开放封闭原则(工厂和类相互独立不耦合,可以对工厂或者类进行扩展)
- 符合依赖倒置原则(工厂依赖IPerson接口,不依赖具体的类,更方便扩展)
代码演示:
interface IPerson { name: string; speak(): void; } class Teacher implements IPerson { constructor(public name: string) {} speak() { console.log(`${this.name}老师说话`); } } class Student implements IPerson { constructor(public name: string) {} speak() { console.log(`${this.name}同学说话`); } } class Parent implements IPerson { constructor(public name: string) {} speak() { console.log(`${this.name}家长说话`); } } function create(type: string, name: string): IPerson { if (type === 'student') { return new Student(name); } if (type === 'teacher') { return new Teacher(name); } if (type === 'parent') { return new Parent(name); } throw new Error('输入的参数不正确'); } const p1 = create('student', '小明'); const p2 = create('teacher', '王皓'); const p3 = create('parent', '田雨'); p1.speak(); p2.speak(); p3.speak();
UML类图:
应用场景
- jQuery
- Vue
- React createElement
jQuery
如下伪代码示例:
// 扩展window属性 declare interface Window { $: (selector: string) => JQuery; } class JQuery { constructor(selector: string) { const arr: any[] = [...document.querySelectorAll(selector)]; arr.forEach((item, index) => { // @ts-ignore this[index] = item; }); } removeClass() { //... return this; } addClass() { //... return this; } } function $(selector: string) { return new JQuery(selector); } window.$ = $;
这篇关于【十月打卡】第70天 前端常用的7种设计模式(6)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 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专业技术文章分享