前端设计模式应用

article/2025/10/22 13:30:34

前端设计模式应用


什么是设计模式

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

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

设计模式背景

  1. 模式语言:城镇、建筑、建造 (A Pattern Language:Towns, Buildings,Construction)1977
  2. 设计模式:可复用面向对象软件的基础 (Design Patterns: Elements of
    ReusableObject-Oriented Software)1994

设计模式趋势
在这里插入图片描述
设计模式分类

23种设计模式

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

浏览器中的设计模式

单例模式

定义:
全局唯一访问对象

应用场景:
缓存, 全局状态管理等。

单例模式请求缓存

//定义api,500m后返回
import { api } from”./utils" ;export cLass Requset {//定义请求实例static instance: Requset;//定义缓存private cache: Recordestring, 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[urU]){ 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);
});
	import { api } from "./utils";const cache: Record<string, string> = {};export const request = async (urT: string){if (cache[urL]) {return cache[urL];}const response = await api(urL);cache[urL] = response;return response;
};
	test(" should response quickly second time", async 0) = { await request(" /user/1");const startTime = Date. now() ;await request(" /user/1");const endTime = Date. now() ;const costTime = endTime - startTime;expect (costTime) . toBeLessThan(50) ;
});

发布订阅模式

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

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

type Notify = (user: User) => void;export class User {name: string;status: "offline" | "online";// user 订阅自己的人,notify 上线时的通知函数followers: { user: User; notify: Notify }[];constructor(name: string) {this.name = name;this.status = "offline";this.followers = [];}// 订阅参数中的 usersubscribe(user: User, notify: Notify) {user.followers.push({ user, notify });}// 上线online() {// 状态改为 onlinethis.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");// 通知 user1 和 user2 的函数const mockNotifyUser1 = jest.fn();const mockNotifyUser2 = jest.fn();// user1 订阅了 user3 的上线,传入通知 user1 的函数user1.subscribe(user3, mockNotifyUser1);user2.subscribe(user3, mockNotifyUser2);// user3 上线user3.online();// user3 会调用通知 user1 的函数expect(mockNotifyUser1).toBeCalledWith(user3);expect(mockNotifyUser2).toBeCalledWith(user3);
});

Javascript中的设计模式

原型模式

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

应用场景 :
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) => {// Object.create(obj) 会根据已有的对象返回一个新的对象// baseUser 是原型,与新创建的对象是继承关系const user: User = Object.create(baseUser);user.name = name;user.followers = [];return user;
};
test("should notify followers when user is online for multiple users", () => {const user1 = createUser("user1");const user2 = createUser("user2");const user3 = createUser("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;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);//   });// }// online 只做上线一件事情,单一职责原则online() {this.status = 'online'}
}// 实现通知
export const createProxyUser = (name: string) => {const user = new User(name);// 使用 new Proxy() 实现代理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;
};

迭代器模式

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

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

用 for of 迭代所有组件

// 浏览器中的 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 {// for...of 迭代时调用的函数next: () => {while ((node = list.shift())) {// 层序遍历node.children.length > 0 && list.push(...node.children);// value 是迭代出的值,done 是指迭代是否完成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);
});

前端框架中的设计模式

Vue 组件实现计数器

<template><button @click="count++">count is: {{ count }}</button>
</template><script setup lang="ts">
import { ref } from "vue ";
const count = ref(0);
</script>

没有框架之前,我们通过监听 click 事件,通过 innerText 手动改变 DOM 的属性。前端框架对 DOM 操作进行代理,模板中的 DOM 都是 Proxy 代理后的虚拟 DOM,我们的操作的 DOM 是虚拟 DOM,之后通过 Diff 对视图更新。

在这里插入图片描述
组合模式

定义:
可多个对象组合使用成为一个单独的对象,也可以单个对象独立使用

应用场景:
DOM,前端组件,文件目录

React 的组件结构

export const Count = () => {const [count, setCount] = useState(0);return (<button onClick={() => setCount((count) => count + 1)} >count is: {count}</button >);
};
function App() {return (<div className="App"><Header /><Count /><Footer /></div>);
}

总结

设计模式不是银弹。

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

http://chatgpt.dhexx.cn/article/iKw87Bvd.shtml

相关文章

web端设计和web前端开发的区别

Web前端开发技术主要包括三个要素&#xff1a;HTML、CSS和JavaScript&#xff01; 它要求前端开发工程师不仅要掌握基本的Web前端开发技术&#xff0c;网站性能优化、SEO和服务器端的基础知识&#xff0c;而且要学会运用各种工具进行辅助开发以及理论层面的知识&#xff0c;包括…

前端开发中常用设计模式-总结篇

本文是向大家介绍前端开发中常用的设计模式&#xff0c;它使我们编写的代码更容易被复用&#xff0c;也更容易被人理解&#xff0c;并且保证代码的稳定可靠性。 1.什么是设计模式 通俗来讲&#xff0c;就是日常使用设计的一种惯性思维。 因为对应的这种思维&#xff0c;以及对…

前端的设计模式有哪些呢

谈谈设计模式~ 文章目录 什么是设计模式设计模式分类1. 结构型模式2. 创建型模式3. 行为型模式具体使用 什么是设计模式 设计模式&#xff0c;是对软件设计开发过程中反复出现的某类问题的通用解决方案。设计模式是指一种思想和方法论&#xff0c;先有设计思想&#xff0c;才能…

【面试】最新web前端经典面试题试题及答案(持续更新)-html/css、js、vue、http、web安全、前端性能、浏览器、js算法

author: aSuncat JavaScript知识点大全&#xff1a;https://www.yuque.com/webfront/js 所有最新最全面试题&#xff0c;持续更新在语雀。见 语雀-前端面试题&#xff0c;欢迎点击关注~ 阅读目录 html/ css&#xff1a;https://blog.csdn.net/aSuncat/article/details/88789368…

为什么说前端一定要学好设计模式?

设计模式&#xff08;Design Pattern&#xff09;大家一定不陌生。通俗地讲&#xff0c;它是前辈们对代码开发经验的总结&#xff0c;让你写出可扩展、可读、可维护的高质量代码&#xff0c;还能让你在遇到相似的问题、场景时&#xff0c;快速找到更优的解决方案。 也许你会说&…

前端JS设计模式

什么是设计模式 软件设计模式&#xff08;Design pattern&#xff09;&#xff0c;又称设计模式&#xff0c;是一套被反复使用、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了可重用代码、让代码更容易被他人理解、保证代码可靠性、程序的重用性。 比…

前端开发中常用的几种设计模式有哪些

设计模式概览 设计模式是对软件设计开发过程中反复出现的某类问题的通用解决方案。设计模式更多的是指导思想和方法论&#xff0c;而不是现成的代码&#xff0c;当然每种设计模式都有每种语言中的具体实现方式。学习设计模式更多的是理解各种模式的内在思想和解决的问题&#…

前端需要了解的9种设计模式

前端需要了解的9种设计模式 什么是设计模式&#xff1f; 设计模式是对软件设计开发过程中反复出现的某类问题的通用解决方案。设计模式更多的是指导思想和方法论&#xff0c;而不是现成的代码&#xff0c;当然每种设计模式都有每种语言中的具体实现方式。学习设计模式更多的是…

前端设计模式

作为一个前端新人&#xff0c;学习了设计模式以后&#xff0c;希望能从源头上&#xff0c;用浅显易懂的语言来解释它。当然不一定是正确的&#xff0c;只是我个人对设计模式的一点浅显理解。 创建型设计模式 创建型设计模式&#xff1a;故名思意&#xff0c;这些模式都是用来创…

web前端设计模式

文章目录 浅谈设计模式1.设计模式是什么2.为什么要学设计模式3.SOLID设计原则4.设计模式的核心思想—封装变化5.23种常见设计模式 创建型一、工厂模式&#xff08;Factory Pattern&#xff09;简单工厂1.解决的问题&#xff1a;2.构造器3.使用步骤4.举例 抽象工厂 &#xff08;…

前端常用的8种设计模式

文章目录 1.引入2.单例模式3.装饰器模式3.适配器模式4.观察者模式&#xff08;发布订阅模式&#xff09;5.策略模式6.模板模式7.代理模式8.外观模式9.面试点 1.引入 简介&#xff1a; 设计模式代表了最佳的实践&#xff0c;通常被有经验的面向对象的软件开发人员所采用。设计…

前端JavaScript中常见设计模式

1、为啥会有这一篇 &#xff1f; 前两天有个同学问我&#xff0c;然后组内同学也即将分享相关实践内容&#xff0c;此处 在他之前发出&#xff08;早一天发布的发布会&#xff09;&#xff0c;good! 2、是何物&#xff1f; 组件化是前端非常重要的一块内容&#xff0c;现在流…

你必须要会的4种Web前端设计模式

在软件工程领域&#xff0c;设计模式是为了解决特定问题而产生的一些可复用的方法、模板。每一种设计模式都针对性解决某一类场景的问题。设计模式被认为是开发者解决通用问题的最佳实践。 通常我们学习的设计模式&#xff0c;大多数与面向对象的语言相关&#xff0c;比如Java。…

前端开发中常用的几种设计模式

设计模式概览 设计模式是对软件设计开发过程中反复出现的某类问题的通用解决方案。设计模式更多的是指导思想和方法论&#xff0c;而不是现成的代码&#xff0c;当然每种设计模式都有每种语言中的具体实现方式。学习设计模式更多的是理解各种模式的内在思想和解决的问题&#…

图像金字塔原理

一、图像缩小 先高斯模糊&#xff0c;再降采样&#xff0c;需要一次次重复&#xff0c;不能一次到底 二、图像扩大 先扩大&#xff0c;再卷积或者使用拉普拉斯金字塔 三、金字塔类型 1、高斯金字塔 用于下采样。 高斯金字塔是最基本的图像塔。 原理&#xff1a;首先将原图…

【编程】金字塔图案

1&#xff0e;问题描述 打印出金字塔图案&#xff0c;如图1.1所示。 图1-1 2&#xff0e;问题分析 这个问题是一个很经典的循环应用的题目。我们都知道&#xff0c;打印输出的时候&#xff0c;都是从最左端输出&#xff0c;而这里&#xff0c;第一个星号是在中间。这实际是…

计算机视觉-OpenCV图像金字塔

&#x1f60a;&#x1f60a;&#x1f60a;欢迎来到本博客&#x1f60a;&#x1f60a;&#x1f60a; 本次博客内容将继续讲解关于OpenCV的相关知识 &#x1f389;作者简介&#xff1a;⭐️⭐️⭐️目前计算机研究生在读。主要研究方向是人工智能和群智能算法方向。目前熟悉pytho…

图像金字塔(image pyramid) 分为两种:高斯金字塔  和  拉普拉斯金字塔。

高斯金字塔 高斯金字塔模仿的是图像的不同的尺度&#xff0c;尺度应该怎样理解&#xff1f;对于一副图像&#xff0c;你近距离观察图像&#xff0c;与你在一米之外观察&#xff0c;看到的图像效果是不同的&#xff0c;前者比较清晰&#xff0c;后者比较模糊&#xff0c;前者比…

数字图像处理:图像金字塔

转载请标明出处&#xff1a;数字图像处理&#xff1a;图像金字塔_数字图像处理opencv_新浪博客 &#xff08;一&#xff09;概念 以多个分辨率来表示图像的一种有效且概念简单的结构是图像金字塔。图像金字塔最初用于机器视觉和图像压缩&#xff0c;一个图像金字塔是一系列以金…

图像处理-图像金字塔

图像金字塔&#xff08;image pyramid&#xff09;&#xff0c;一般有两种&#xff1a;高斯金字塔、拉普拉斯金字塔 ——————————————————————————————— 先介绍下里面的一些操作&#xff1a; 下采样&#xff1a;相当于对图像进行一个像素的抽取&a…