设计模式简述 | 青训营笔记
这是我参与「第四届青训营 」笔记创作活动的第4天
简介
-
设计模式是软件设计中,历史经验的总结
-
设计模式与特定语言无关,而是一种思想
设计模式类型
-
创建型-如何创建一个对象
-
结构型-如何灵活的将对象组装成较大的结构
-
行为型-负责将对象间的高效通信和职责划分
浏览器中的设计模式
单例模式
- 定义:全局唯一的访问对象。
- 应用场景:缓存、全局状态管理。
利用单例模式实现请求缓存
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 response = await api(url);
this.cache[url] = response;
return response;
}
}
从代码中看到,getInstance方法在已经存在instance时,直接返回instance,而不存在instance时则创建一个instance对象,从而使instance属性始终保持只有一个。
request则为缓存方法,当缓存中存在该url时,直接返回,否则去请求url并缓存;这样就使相同的请求速度大大加快,且减小了后端服务器的压力。
发布订阅模式
- 定义:订阅机制,可在被订阅的对象发生变化时通知订阅者。
- 应用场景: 从系统架构之间的解耦,到业务中的一些实现模式,想邮件订阅,上线订阅等。
利用发布订阅模式实现用户上线订阅
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);
});
}
}
其中的构造方法定义了每个用户名称,默认状态以及订阅者。
subscribe订阅方法通过传入被订阅的对象与通知方法,将自己添加入被订阅对象的followers数组中,当被订阅方上线时,执行online方法遍历followers数组,即可通知到订阅方。
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) =>{
const user: User = Object.create(baseUser);
user.name = name;
user.followers = [];
return user;
};
createUser方法通过Object.create方法,基于已有的baseUser对象,返回一个新的对象,baseUser作为新的象的原型,实际为继承关系,创建对象时,不需要new,而是直接调用createUser方法。
代理模式
定义:可自定义控制对原对象的访问方式,并且允许在更新前后做一些额外处理。
应用场景:监控,代理工具,前端框架实现等。
利用代理模式实现用户状态订阅
基于发布订阅模式的改进
将online方法更改为:
online(){
this.status = "online";
}
而没有其他的操作,不在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;
};
其中Proxy代理方法可以监测到user中数值的变化,其中Proxy的第一个参数代表代理的对象,第二个参数是对对象操作方法的监视,一般有get与set,还有deleteProperty方法用于删除属性时的监控。当status赋值为"online"时,status的set方法被代理,赋值后同时执行notifyStatusHandlers方法。
迭代器模式
- 定义:在不暴露数据类型的情况下访问集合中的数据。
- 应用场景:数据结构中有多种数据类型,列表,树等,提供通用操作接口。
利用for of 迭代所有组件
为类添加[Symbol.iterator]方法,使之可迭代。
[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};
},
};
}
每次for of时调用的函数,返回value与done,done代表是否结束,value代表值。
前端框架中的设计模式
代理模式
const p = new Proxy(person, {
get(target, propName) {
return target[propname];
},
set(target, propName, value) {
target[propName] = value;
},
deleteProperty(target, propName) {
return delete target[propName];
},
});
vue3中响应式原理是以Proxy代理为基础。
更改DOM属性------------》更新虚拟DOM-------diff------》视图更新
其中虚拟DOM就是真实DOM的代理。
组合模式
-
定义:可多个对象组合使用,也可单个对象独立使用。
-
应用场景:DOM,前端组件,文件目录,部门
总结
- 总结出抽象的模式相对比较简单,但是想要将抽象的模式套用到场景中却非常困难。
- 现代编程语言的多编程范式带来更多可能性。
- 真正优秀的开源项目学习设计模式并不断实践。