前端设计模式应用

177 阅读2分钟

什么是设计模式

23种设计模式

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

浏览器的设计模式

单例模式

定义

全局唯一访问对象

应用场景

缓存、全局状态管理等

用单例模式实现请求缓存

两个实例 控制的是一个全局对象 全局唯一

class类方法

import {api} from './utils';
export class Request{
    static instance:Request;
    private cache: Record<string,string>
    
    constructor(){
        this.cache = {}
    }
    
    static getInstance(){
        if(this.instance){
            return this.instance;
        }
        this.instance = new Request()
        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
    }
}

函数方法

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
}

发布订阅模式

定义

一种订阅机制,可在被订阅对象发生变化时通知订阅者

应用场景

从系统架构之间的解耦,到业务中一些实现模式,像邮件订阅,上线订阅等等,应用广泛。

JavaScript 中的设计模式

原型模式

定义

复制已有对象创建新的对象

应用场景

JS中对象创建的基本模式

代理模式

定义

可自定义控制对原对象的访问模式,并且允许在更新前后做一些额外处理

应用场景

监控、代理工具、前端框架实现等等

迭代器模式

定义

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

应用场景

数据结构中有多种数据类型,列表,树等,提供通用操作接口

前端框架中的设计模式

代理模式

定义

应用场景

修改dom

组合模式

定义

可多个对象组合使用,也可单个对象独立使用

应用场景

DOM、前端组件、文件目录、部门