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

50 阅读3分钟

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

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

一, 什么是设计模式?

简单点来讲,设计模式就是软件设计中常见问题的解决方案模型。

  1. 常见问题:历史经验的总结 。
  2. 解决方案模型:与特定语言无关。

二,设计模型分类

23种设计模型

  • 创建型:如何创建一个对象。
    • 对对象的实例化过程进行抽象。
    • 工厂方法模式、抽象工厂模式、单例模式、建造者模式、原型模式。
  • 结构型:如何灵活的将对象组装成较大的结构。
    • 通过对多个类和对象进行组合得到复杂结构的类。
    • 适配器模式、装饰器模式、代理模式、外观模式、桥接模式、组合模式、享元模式。
  • 行为型:负责对象间的高效通信和职责划分。
    • 策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式。
    • 两个特殊模式:并发型模式和线程池模式。

三,浏览器中的设计模型

3.1 单例模式

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

具体例子:

用单例模式实现请求缓存:

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 Requset(url:string){
        if(this.cache[url]){
            return this.cache[url];
        }
        const response = await api(url);
        this.cache[url]=response;
        return response;
    }
}

3.2 发布订阅模式

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

具体例子:

const button=document.getElementById("button");

const doSomthing1 =()=>{
    console.log("Send message to user");
};

const doSomthing2 =()=>{
    console.log("Log...");
};

button addEventListener("click",doSomthing1);
button addEventListener("click",doSomthing2);

四,Javascript中的设计模型

4.1 原型模式

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

具体例子:

const bassUser:user={
    name:"",
    status:"offline",
    followers:[],
    subscribe(user,notify){
        user.followers.push({user,notify});
    },
    online (){
        this.status="online";
        thiis.follower.forEach(({notify})=>{
            notify(this);
        });
    },
};

export const createUser =(name:string)=>{
    const user:User = object.create(baseUser);
    user.name=name;
    user.followers =[];
    return user;
};

4.2 代理模式

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

具体例子:

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.notufy});
    }

    online(){
        this.status ="online";
        this.followers.forEach(({notify})=>{
            notify(this);
        });
    }
}

4.3 迭代器模式

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

具体例子:

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){
    //...
}

五,前端框架中的设计模型

5.1 代理模式

image.png

具体例子:

Vue组件实现计数器

<template>
    <button @click="count++">count is: {{count}}<button>
</template>

<script setup lang="ts">
    import{ref} from "vue";

    const count =ref(0)
</script>

5.2 组合模式

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

具体例子:

React的组件结构

function App(){
    return(
        <div className="App"> 
        <Hesder />
        <Count />
        <Footer />
        </div>
    );
}