这是我参与「第四届青训营 」笔记创作活动的第5天
一、本堂课重点内容:
讲了浏览器、JS、前端框架等中的设计模式,对设计模式进行了概括。
二、详细知识点介绍:
设计模式:软件设计中常见问题的解决方案模型
23钟设计模式:
- 创建型-如何创建一个对象
- 结构型-如何灵活的将对象组装成较大的结构
- 行为型-负责对象间的高效通信和职责划分
浏览器中的设计模式:
- 单例模式(存在全局唯一访问对象,如window)
应用场景(缓存,全局状态管理)
- 发布订阅模式(一种订阅机制,可以在被订阅对象发生变化时通知订阅者)
应用场景(从系统架构之间的解耦,到业务中的一些实现模式,像邮件订阅,上线订阅等等,应用广泛)
javascript中的设计模式
- 原型模式
- 复制已有对象来创建新的对象
- JS中对象创建的基本模式
- 代理模式
- 可自定义控制对原对象的访问方式,并且允许在更新前后做一些额外处理
- 监控,代理工具,前端框架实现等等
- 迭代器模式
- 在不暴露数据类型的情况下访问集合中的数据
- 数据结构中有多种数据类型,列表,树等,提供通用操作接口
前端框架中的设计模式
- 代理模式
- 组合模式
- 可多个对象组合使用,可也单个对象独立使用
- DOM,前端组件,文件目录,部门
DOM操作:
原来:更改DOM属性-》视图更新
现在:更改DOM属性-》更新虚拟DOM-DIFF-》视图更新
三、实践练习例子:
用单例模式实现请求缓存
export class Request{
static instance: Request;
// 全局唯一的实例
private cache: Record<string,string>;
// 缓存对象
constructor(){
this.cache={};
}
static getInstance(){
if(this.instance){
return this.instance;
}
this.instance = new Request();
return this.instance;
}
public async request(url:string){
if(this.cache[url]){
return this.cache[url];
}
const responce = await api(url);
this.cache[url] = responce;
return responce;
}
}
const cache: Record<string,string>={};
export const request = async (url: string)=>{
if(cache[url]){
return cache[url];
}
const responce = await api(url);
cache[url] = responce;
return responce;
};
用发布订阅模式实现用户上线订阅
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("",()={
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);
});