这是我参与「第四届青训营 」笔记创作活动的第 7 天。(第七篇笔记)
本次学习的内容是 「前端设计模式的应用」,包括讲解了传统的设计模式有哪些是过时的,那些已经在应用中内置的。
设计模式理解
概念
设计模式:软件设计中常见问题的方案模型:
- 常见问题:历史经验的总结
- 解决方案模型:与特定语言无关;是抽象的思想。
背景与趋势
…
分类
有 23 种设计模型,可以分为三类:
- 创建型:如何创建一个对象;
- 结构型:如何灵活地将对象组装成的较大的结构;
- 行为型:负责对象之间的高效通信和职责划分;(对型的分工)
前端设计模式
浏览器中的设计模式
单例模式
- 定义:(
window)全局唯一访问对象; - 应用场景:缓存;全局应用管理;
🌰 例子 / 单例模式实现请求缓存:
impont { 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(560);
};
test("should respohse 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 (url: string) => {
if (cache[url]) {
return cache[url]
}
const response = await api(url)
cache[url] = response
return response
}
可以不用使用一个类来表示这个单例,而是使用一个变量(
cache)来表示这个单例。
test("should response quickly than 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);
};
发布订阅模式
- 定义:一种订阅机制,可以被订阅对象发生变化时通知订阅者;
- 应用场景:从系统之间的解耦,到业务中的一些实现模式,邮件订阅、上线订阅等;
🌰 例子:
const button = document.getElementById("button")
const doSomething1 = () => {
console.log("send message to user")
}
const doSomething2 = () => {
console.log("send message to system")
}
button.addEventListener("click", doSomething1)
button.addEventListener("click", doSomething2)
这里的发布者是点击事件,订阅者是点击事件发生时运行的函数。
🌰 例子 / 订阅模式实现用户上线订阅:
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);
}
user3发布者,user1/user2是订阅者;并且user1/user2/user3可以相互订阅。
JavaScript 的设计模式
原型模式
- 定义:复制已有的对象来创建新的对象;
- 应用场景:JavaScript 中对象创建的基本模式;
🌰 例子 / 原型模式创建上线订阅中的用户:
const baseUser: User = {
name: "",
status: "offline",
followers: [],
subsribe(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 multiple users", () => {
const user1 = new createUser("user1");
const user2 = new createUser("user2");
const user3 = new 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() {
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;
}
迭代器模式
- 定义:不暴露数据类型的情况下,访问集合中的数据;
- 应用场景:(数据结构中的多种数据类型)列表、树等,提供通用接口;
🌰 例子 / 用 for ... of 迭代所有组件:
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 poot element", () => {
const body = new MyElement("body")
const header = new MyElement("header")
const main = new MyElement("main")
const banner = new MyDomELement ("banner");
const content = new MyDomELement("content"):
const footer = new MyDomELement ("footer");
body.addChildren(body)
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 }}
</butto>
</template>
<script setup lang="ts">
import { ref } from 'vue';
const count = ref(0)
</script>
前端框架对 DOM 操作的代理:
之前:更改 DOM 属性 ➡️ 视图更新
现在:更新 DOM 属性 ➡️ 更新虚拟 DOM ➡️(Diff 算法) 视图更新
DOM 更新前后的钩子,也是代理模式的体现。
组合模式
定义:可以多个对象组合使用,也可以单个对象独立使用
应用场景: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>
);
};
总结
- 传统的设计模式也许并不能投入到实际的应用开发,解决实际的问题的范例,但是可以学习设计模式其中的思想。
- 总结出抽象的模式相对比较简单,但是想要将抽象的模式套用到场景非常困难;
- 现代编程语言的多编程范式带来的更多可能性;
- 真正的优秀开源项目都是学习设计模式并且不断实践;
练习使用组件模式实现一个文件夹结构:
- 每个文件夹可以包含文件和文件夹;
- 文件有大小;
- 可以获取每个文件夹下文件的整体大小;