这是我参与[第四届青训营]笔记创作活动的第四天。
什么是设计模式:
设计模式是一套被反复使用的、多数人知晓的、经过分类编目的、代码设计经验的总结。使用设计模式是为了重用代码、让代码更容易被他人理解、保证代码可靠性。 毫无疑问,设计模式于己于他人于系统都是多赢的,设计模式使代码编制真正工程化,设计模式是软件工程的基石,如同大厦的一块块砖石一样。项目中合理地运用设计模式可以完美地解决很多问题,每种模式在现实中都有相应的原理来与之对应,每种模式都描述了一个在我们周围不断重复发生的问题,以及该问题的核心解决方案,这也是设计模式能被广泛应用的原因。
软件设计中常见问题的解决方案模型
- 历史经验的总结
- 与特定语言无关
设计模式趋势:
23种设计模式:
- 创建型-如何创建一个对象
- 结构型-如何灵活的将对象组装成较大的结构
- 行为型-负责对象间的高效通信和职责划分
浏览器中的设计模式:
- 单例模式
- 发布订阅模式
单例模式:
定义:全局唯一访问对象。
应用场景:缓存,全局状态管理。
用单例模式实现缓存请求:
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 Requset();
return this.instance;
}
public async request(url: string) {
if (this.cache[uru]) {
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(500);
});
//只调用一次,没有缓存
test( "should response 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);
});
//调用两次,有缓存
使用JS实现单例(无CSS):
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;
};
test("should response quickly 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);
});
发布订阅模式:
定义:
一种订阅机制,可在被订阅对象发生变化时通知订阅者。
应用场景:
从系统架构之间的解耦,到业务中一些实现模式,像邮件订阅,上线订阅等等。应用广泛。
用发布订阅模式实现用户上线订阅:
type Notify = (user: User) =void;
export class User {
name: string;
status: "offline" | "online";
followers: i 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);
});
Javascript中的设计模式
- 原型模式
- 代理模式
- 迭代器模式
原型模式:
定义:
复制已有的对象来创建新的对象。
应用场景:
JS中对象创建的基本模式。
** 用原型模式创建上线订阅中的用户**
const baseUser: User = {
name: "",
status: "offline" ,
followers: [],
subscribe(user, notify) {
user .followers. push({ user,notify H);
},
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 user prototypes",() ={
const user1 = createUser("user1");
const user2 = createUser( "user2");
const user3 = 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);
});
代理模式:
定义:
可自定义控制原对象的访问方式,并且允许在更新前后做一些额外处理。
应用场景:
监控,代理工具,前端框架实现等等。
使用代理模式实现用户状态订阅:
迭代器模式:
定义:
在不暴露数据类型的情况下访问集合中的数据
应用场景:
数据结构中有多种数据类型、列表、树等,提供通用操作接口。
用for of 迭代所有组件
(Symbol.iterator 使组件变成可迭代的)
前端框架中的设计模式:
- 代理模式
- 组合模式
vue组件实现计数器:
<template>
<button click="countit ">count is: ii count }}</button>
</template>
<script setup lang="ts">import i ref } from "vue" ;
const count = ref(0);
</script>
前端框架中对DOM操作的代理:
组合模式:
定义: 可多个对象组合使用,也可单个对象独立使用。
应用场景: DOM,前端组件,文件目录,部门。
总结:
设计模式不是银弹
- 总结出抽象的模式相对比较简单,但是想要将抽象的模式套用到场景中却非常困难
- 现代编程语言的多编程范式带来的更多可能性
- 真正优秀的开源项目学习设计模式并不断实践