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

74 阅读5分钟

这是我参与「第四届青训营 」笔记创作活动的的第5天

什么是设计模式?

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

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

设计模式分类

23种设计模式

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

浏览器中的设计模式

  • 单例模式
  • 发布订阅模式

单例模式

  • 定义:全局唯一访问对象
  • 应用场景:缓存,全局状态管理等

用单例模式实现请求缓存

在一个页面中,不同时或不同地会发送不同的url请求,为了第二次发送url请求时可复用之前的值,作为缓存,带来更好的用户体验。

import { api } from "./utils";
export class Requset {
    static instance: Requset;//静态方法存储全局唯一的实例
    private cache: Record<string, string>;//存储缓存值
    constructor( {
        this.cache = {};
    }
    //第一次创建新的,后面就用这一个
    static getInstance() {
        if (this.instance) {
            return this.instance;
        }
        
        this.instance = new Requset();
        return this.instance;
    }
    //真正缓存的实现
    public async request(url: string) {
        if (this.cache[url]) {
            return this.cache[url];
        }
        const response = await api(url);
        this.cache[url] = response;
        return response;
    }
}
// 无缓存时
test( "should response more than 500ms with class", async () => {
    const request = Requset.getInstance();
    
    const startTime = Date.now();
    await request.request( "/user/1");
    const endTime = Date.now();
    
    const costTime = endTime - startTime;
    
    expect(costTime).toBeGreaterThanOrEqual(500);
});
//有缓存时
test( "should response quickly second time with class",async () => {
    const request1 = Requset.getInstance();
    await request1.request( "/user/1");
    
    const startTime = Date.now();
    const request2 = Requset.getInstance();
    await request2.request("/user/1");
    const endTime = Date.now();
    
    const costTime = endTime - startTime;
    
    expect(costTime) .toBeLessThan(50);
});

若用js实现:

//定义API
import {api} from './utils';
//定义全局唯一的对象cache
const cache:Record<string,string> = {}
export const request =  async (url:string)=>{
    //如果有则直接返回原来的
    if(cache[url]){
        return cache[url]
    }
    //没有就调用api去获取
    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);
});

发布订阅模式/观察者模式

  • 定义:一种订阅机制,可在被订阅对象发生变化时通知订阅者
  • 使用场景:从系统架构之间的解耦,到业务中一些实现模式,类似邮件订阅,上线订阅,应用广泛 image.png

用发布订阅模式实现用户上线订阅

type Notify = (user: User) void;

export class User {
    name: string;
    status: "offline" | "online" ;
    followers: { user: User; notify: Notify }[];
    
    constructor(name: string) {
        this.name = name;
        this.status = "offline";
        this.followers = [];
    }
    //订阅方法
    subscribe (user: User, notify: Notify) {
        user.followers.push({ user, notify });
    }
    
    online() {
        this.status = "online";
        this.followers.forEach(({ notify }) => {
            notify (this);
        });
    }
}
test("should notify followers when user is online for multiple users",() => {
    const user1 = new User("user1");
    const user2 = new User("user2");
    const user3 = new User("user3");
    
    const mockNotifyUser1 = jest.fn();
    const mockNotifyUser2 = jest.fn();
    
    user1.subscribe(user3, mockNotifyUser1);
    user2.subscribe(user3, mockNotifyUser2);
    
    user3.online();
    
    expect(mockNotifyUser1).toBeCalledWith(user3);
    expect(mockNotifyUser2).toBeCalledWith(user3);
});

Javascript中的设计模式

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

原型模式

  • 定义:复制已有的对象,来生成新的对象
  • 应用场景:JS中对象创建的基本模式

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

//定义自变量对象baseUser
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;
}
test("should notify followers when user is online for user prototypes",() => {
    const user1 = creatUser("user1");
    const user2 = creatUser("user2");
    const user3 = creatUser("user3");
    
    const mockNotifyUser1 = jest.fn();
    const mockNotifyUser2 = jest.fn();
    
    user1.subscribe(user3, mockNotifyUser1);
    user2.subscribe(user3, mockNotifyUser2);
    
    user3.online();
    
    expect(mockNotifyUser1).toBeCalledWith(user3);
    expect(mockNotifyUser2).toBeCalledWith(user3);
});

代理模式

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

使用代理模式实现用户状态订阅

type Notify = (user: User) => void;
class User {
    name: string;
    status: "offline" | "online" ;
    followers: { user: User; notify: Notify }[];
    
    constructor(name: string) {
        this.name = name;
        this.status = "offline";
        this.followers = [];
    }

    subscribe (user: User, notify: Notify) {
        user.followers.push({ user, notify });
    }
    
    online() {
        this.status = "online"; 
    }
    }
export const createProxyUser = (name:string)=>{
    const user = new User(name);
    const proxyUser = new Proxy(user,{
        set:(target,prop:keyof User,value)=>{
            target[prop]=value;
            if(prop === "status"){
                notifyStatusHandlers(target,value)
            }
            return true;
        },
    });
    const notifyStatusHandlers = (user:User,status:'online'|'offline'=>{
    	if(status === "online"){
        	user.followers.forEach(({notify})=>{
                notify(user);
            })
    	}                              
    };
    return proxyUser;
};

使用方式同上

迭代器模式

  • 定义:在不暴露数据类型的情况下访问集合中的数据
  • 应用场景:数据结构中有多种数据类型,列表,树等,提供通用操作接口 image.png

用for of迭代所有组件

//模拟一个DOM结构
class MyDomElement{
  tag:string;
  children:MyDomElement[];
  constructor(tag:string){
    this.tag=tag;
    this.children=[];
  }
  
  addChildren(component:MyDomElement){
    this.children.push(component);
  }
  //添加js中特殊内置方法iterator,使此组件变为可迭代的
  [Symbol.iterator](){
  //定义初始化list为自己的子组件
    const list=[...this.children];
    let node;
    
    return{
      next:()=>{
        while((node=list.shift())){//每次拿到子组件中一个独立的node,若这个node有children,就把它push到整体的list上(先序遍历)
          node.children.length>0 && list.push(...node.children);
          
          return{value:node,done:false};//value为迭代出的值,flase表示迭代结束
        }
        return{value:null,done:true};
      },
    };
  }
} 

使用: image.png

前端框架中的设计模式

  • 代理模式
  • 组合模式

代理模式

Vue组件实现计数器

button监听一个click的函数,并把count渲染出来 image.png

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

image.png

组合模式

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

React的组件结构

image.png 可独立被渲染 image.png

总结

设计模式不是银弹,并不能解决所有问题

  • 总结出抽象的模式相对比较简单,但是想要将抽象的模式套用到场景中却非常困难
  • 现代编程语言的多编程范式带来的更多可能性
  • 真正优秀的开源项目学习设计模式并不断实践