前端设计模式|青训营笔记

60 阅读4分钟

前端设计模式|青训营笔记

这是我参与「第四届青训营 」笔记创作活动的的的第五天,今天了解了一些常用的设计模式,展望了设计模式的前景。

本堂课重点内容

  • 设计模式背景
  • 设计模式趋势
  • 设计模式分类
  • 浏览器中的设计模式
  • Javascript中的设计模式
  • 前端框架中的设计模式

详细知识点介绍

一、前言

什么是设计模式?

软件设计中常见问题的解决方案模型

  • 历史经验的总结
  • 与特定语言无关

设计模式背景

  1. 《模式语言:城镇、建筑、建造》1977
  2. 《设计模式·可复用面向对象软件的基础》1994

设计模式趋势

屏幕截图 2022-08-17 195130.png

二、设计模式分类

23种设计模式

  • 创建型:如何创建一个对象
  • 结构型:如何灵活的将对象组装成较大的结构
  • 行为型:负责对象间的高效通信和职责划分

三、浏览器中的设计模式

3.1 单例模式

  • 定义:全局唯一访问对象

  • 应用场景:缓存、全局状态管理

  • 例子:浏览器中的Window对象

  • 单例模式实现请求缓存

    • ts实现

微信图片_20220817195239.bmp

  • js实现

    import {api} from "./utils";
    const cache : Record<string, string> = {};
    export const request = async (url: string) => {
        if (cache[url]) return cache[url]; // 缓存池中有数据就返回
        const response = await api(url); // 没有数据就等待接口返回数据
        cache[url] = response;
        return response;
    }
    复制代码
    
    test("should response quickly second time", async () =>{
    	await request("user/1");
    	const startTime = Date.now();
        await request("user/1");
    	const endTime = Date.now();
        
        const costTime = endTime - startTime;
        expect(costTime).toBeLessThan(50);
    });
    复制代码
    

3.2 发布订阅模式

又叫观察者模式

  • 定义:一种订阅机制,可在被订阅对象发生变化时通知订阅者
  • 应用场景:从系统架构之间的解耦,到业务中一些实现模式,像邮件订阅、上线订阅,到vue框架中组件间通信的机制等等,应用场景十分广泛
  • 实现用户上线订阅

微信图片_20220817195446.bmp

微信图片_20220817195459.bmp

四、Javascript中的设计模式

  • 原型模式
  • 代理模式
  • 迭代器模式

4.1 原型模式

  • 定义:复制已有对象来创建新的对象

  • 应用场景:JS中对象创建的基本模式

  • 用原型模式创建上线订阅中的用户

    const baseUser: User = {
        name: "",
        status: "offline",
        followers: [],
        subscribe(user, notify) {
            user.followers.push({user, notify});
        }
        online() {
    		this.status = "online";
            this.followers.forEach(({notify})=>{
                notify(this);
            });
        }
    }
    export const createUser = (name: string) => {
        const user: User = Object.create(baseUser);
        user.name = name;
        user.followers = [];
        return user;
    }
    复制代码
    

微信图片_20220817195803.bmp

4.2 代理模式

  • 定义:可自定义控制对原对象的访问与写入方式,并且允许在更新前后做一些额外处理
  • 应用场景:监控、代理工具、前端框架实现等等
  • 实现用户上线订阅

微信图片_20220817195814.bmp

4.3 迭代器模式

  • 定义:在不暴露数据类型的情况下访问集合中的数据

  • 应用场景:数据结构中有多种数据类型、列表、树等,提供通用的操作接口

  • javascript基础数据结构中的应用

    const numbers = [1, 2, 3];
    const map = new Map();
    map.set("k1", "v1");
    map.set("k2", "v2");
    const set = new Set(["1", "2", "3"]);
    
    for (const number of numbers){
    	// ...
    }
    for (const [key, value] of map){
    	// ...
    }
    for (const key of set){
    	// ...
    }
    复制代码
    
  • 案例:Dom结构

    class MyDomElement {
    	tag: string;
    	children: MyDomElement[];
    	constructor(tag: string){
    		this.tag = tag;
    		this.children = [];
    	}
    	
    	addChildren(component: MyDomElement) {
    		this.children.push(component);
    	}
        [Symbol.iterator]() {
            const list = [...this.children];
            let node;
            return {
                next: ()=>{
                    while ((node=list.shift())) {
                        node.children.length > 0 && list.push(...node.children);
                        return {value: node, done: false};
                    }
                    return {value: null, done: true};
                }
            }
        }
    } 
    复制代码
    
    test("can iterate root element", ()=>{
    	const body = new MyDomElement("body");
    	const header = new MyDomElement("header");
    	const main = new MyDomElement("main");
    	
    	const banner = new MyDomElement("banner");
    	const content = new MyDomElement("content");
        
        const footer = new MyDomElement("footer");
        
        body.addChildren(header);
        body.addChildren(main);
        body.addChildren(footer);
        
        main.addChildren(banner);
        main.addChildren(content);
        
    	const expectTags: string[] = [];
    	for (const element of body){
    		if (element) expectTags.push(element.tag);
    	}
    	expect(expectTags.length).toBe(5)
    })
    复制代码
    

五、前端框架中的设计模式

  • 代理模式
  • 组合模式

5.1 代理模式

Vue组件实现计数器,正是代理模式起的作用

前端框架中对DOM操作的代理

微信图片_20220817200156.bmp

5.2 组合模式

  • 定义:可多个对象组合使用,也可单个对象独立使用
  • 应用场景:DOM,前端组件,文件目录,部门

课后个人总结

设计模式不是银弹,要辩证的看待传统设计模式的能力

  • 总结出抽象的模式相对比较简单,但是想要将抽象的模式套用到场景中却非常困难;例:软件开发中单一值的原则,即:单一方法、单一类尽量只做一件事,但实际场景中很难定义什么是”一件事情“
  • 现代编程语言的多编程范式带来的更多可能性
  • 真正优秀的开源项目学习设计模式并不断实践

引用参考

www.cnblogs.com/smlp/p/9776…