这是我参与「第四届青训营 」笔记创作活动的第2天
一、设计模式的分类23种
这里课上没有详细说,课后查阅资料如下:
1.1创建型模式
这些设计模式提供了在创建对象同时隐藏创建逻辑的方式,而不是用 new 运算符直接实例化对象。这使程序在判断针对某个给定实例时需要创建哪些对象的时候更加灵活。
包括以下几种:
- 工厂模式(Factory Pattern)
- 抽象工厂模式(Abstract Factory Pattern)
- 单例模式(Singleton Pattern)
- 建造者模式(Builder Pattern)
- 原型模式(Prototype Pattern)
1.2结构型模式
这些设计模式关注类和对象的组合。继承的概念被用来组合接口和定义组合对象获得新功能的方式。
包括以下几种:
- 适配器模式(Adapter Pattern)
- 桥接模式(Bridge Pattern)
- 过滤器模式(Filter、Criteria Pattern)
- 组合模式(Composite Pattern)
- 装饰器模式(Decorator Pattern)
- 外观模式(Facade Pattern)
- 享元模式(Flyweight Pattern)
- 代理模式(Proxy Pattern)
1.3行为型模式
这几种设计模式会特别关注对象之间的通信
包括以下几种:
- 责任链模式(Chain of Responsibility Pattern)
- 命令模式(Command Pattern)
- 解释器模式(Interpreter Pattern)
- 迭代器模式(Iterator Pattern)
- 中介者模式(Mediator Pattern)
- 备忘录模式(Memento Pattern)
- 观察者模式(Observer Pattern)
- 状态模式(State Pattern)
- 空对象模式(Null Object Pattern)
- 策略模式(Strategy Pattern)
- 模板模式(Template Pattern)
- 访问者模式(Visitor Pattern)\
二、浏览器中的设计模式
2.1单例模式(Singleton Pattern)
定义:全局唯一访问对象
应用场景:缓存,全局状态管理等
`import {api}from"./utils";
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 respond=await api(url);//无缓存再去获取url,并保存
this.cache[url]=respond;
}
}`
第一个test里面,无缓存,调用时间超过500ms
第二个test里,二次调用时因为有缓存,所以时间很小\
在JavaScript中如何实现单例:
2.2发布订阅模式
这是一种订阅机制,可以在被订阅对象发生变化时通知订阅者
应用场景:从系统架构之间的解耦,到业务中的一些实现模式,像邮件订阅,上线订阅等等,应用广泛。
用发布订阅模式实现用户上线订阅: