前端设计模式应用|青训营笔记
这是我参与「第四届青训营 」笔记创作活动的的第4天
什么是设计模式
设计模式是软件设计中常见问题的解决方案模型。常见问题是历史经验的总结,解决方案模型与特定语言无关的一个模型
设计模式分类(23种)
- 创建型-如何创建一个对象
- 结构型-如何灵活的将对象组装成较大的结构
- 行为型-负责对象间的高效通信和职责部分
浏览器中的API设计模型
- 单例模式 全局唯一一个访问对象。运用场景是缓存,全局状态管理等。
单例模式实现请求缓存
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 Requseto;
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;
}
}
JavaScript实现
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;
};
- 发布订阅模式 一种订阅机制,可在被订阅对象发生变化时通知订阅者。应用场景是从系统架构之间的解耦,到业务中的一些实现模式,像邮件订阅,上线订阅等等,应用广泛。
用发布订阅模式实现用户上线订阅
type Notify = (user: User) void;
export class User {
name: string;
status: "offline" l"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);
});
}
}
JavaScript中的设计模式
- 原型模式 复制已有对象来创建新的对象,js中对象创建的基本模式
export const createUser = (name: string) =>{
const user: User = Object.create(baseUser);
user.name = name;
user.followers = [];
return user;
};
- 代理模式 可以自定义控制原对象的访问方式,并且允许在更新前后做一些额外处理。应用场景有监控,代理工具,前端框架实现等等。
const notifyStatusHandlers = (user: User,status: "online" | "offline") =>{
if (status"online") {
user.followers.forEach(({ notify })=>{
notify(user);
});
}
};
- 迭代器模式 在不暴露数据类型的情况下访问集合中的数据。场景如下数据结构中有多种数据类型,列表,树等。提供通用操作接口。
[ symbol.iterator]() {
const list =-[ ...this.children];
let node;
return {
next:()=>{
while ((node = list.shift())) {
node.children.length > 08& list.push( ...node.children);
return { value: node, done: false };
}
return { value: null, done: true };
},
};
}
前端框架中的设计模式
- 代理模式
对DOM操作的代理
- 组合模式 可多个对象组合使用,也可单个对象独立使用,场景:DOM,前端组件,文件目录,部门。
function App(){
return(
<div>
<Header />
<Count />
<Footer />
</div>
);
}
抽象的模式相对简单,但是将抽象的模式套用到场景中是非常困难的,设计模式也不是马上可以帮助解决到很多问题,现代编程语言的多编程范式带来更多可能性,我们还需要学习设计模式,不断实践。