这是我参与「第四届青训营 」笔记创作活动的第4天
前端设计模式应用
设计模式的分类(23种)
- 创建型:如何创建一个对象
- 结构型:如何灵活的将对象组装成较大的结构
- 行为型:负责对象间的高效通信和职责划分
- ·······
浏览器中设计模式
单例模式
- 定义 :全局唯一访问对象
- 应用场景:缓存、全局状态管理····
用单例模式实现请求缓存:
import{api} from "./utils";
const cache:Record<string,string>={};
export const request =asynv(url:string)=>{
if (cache[url]){
return cache[url];
}
const response =await api(url);
cache[url]=response;
return response;
};
test("第二次的快速反应",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 doSomthing1 =()=>{
console.log("发送消息给用户");
};
const doSomthing2=()=>{
consle.log("Log····");
};
button.addEventListener("click",doSomthing1);
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.follwers.push({user,notify});
}
online(){
this.stayus="online";
this.followers.forEach(({notify})=>{
notify(this);
})
}
}
test("当前用户上线,通知关注者",()=>{
const user1=new User("user1");
const user2=new User("user2");
const user3=new User("user3");
const mockNotfyUser1=jest.fn();
const mockNotfyUser2=jest.fn();
user1.subscribe(user3,mockNotifyUser1);
user2.subscribe(user3,mockNotifyUser2);
user3.online();
exprct(mockNotfyUser1).toBeCalledWith(user3);
exprct(mockNotfyUser2).toBeCalledWith(user3);
});
JavaScript种的设计模式
原型模式
- 定义:复制已有的对象来创建新的对象。
- 应用场景:JS种对象创建的基本模式。
- 用原型模式创建上线订阅中的用户。
代理模式
- 定义:可自定义控制对原对象的访问方式,并且允许在更新前后做一些额外处理。
- 应用场景:监控、代理工具,前端框架实现···
- 使用代理模式实现用户状态订阅
迭代器模式
- 定义:在不保留数据类型的情况下访问集合中的数据。
- 应用场景:数据结构中有多种数据类型,列表,树等,提供通用操作接口。
- 用 for of迭代所以组件: