-
浏览器中的设计模式
-
单例模式
概念——全局唯一访问对象;
window对象,全局缓存,线程池就是一个符合单例模式的全局唯一对象;
单例模式常见的几种构造方式:
-
懒汉
-
class Request { static instance:Request; static getInstance(){ if(this.instance){ return this.instance; } this.instance = new Request() return this.instance; } }
-
-
饿汉
-
class Request { static instance:new Request(); static getInstance(){ return this.instance; } }
-
-
发布订阅模式
概念——一种订阅机制,可在订阅对象发生变化时通知订阅者
addEventListener就是典型的发布订阅模式;
发布订阅模式和监察者模式的关系区别众说纷纭,可认作同一种模式(大概)
-
JavaScript中的设计模式
-
原型模式
概念——复制已有对象来创建新的对象
原型链的继承就是原型模式
原型链继承
const Parent = Function(){
this.name = 'Parent'
}
const Child = Function(){
this.value = 'Child'
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
原型式继承
Object.create(obj)
函数借用
const Parent = Function(age){
this.name = age
}
const Child = Function(num){
借用函数必须使用call才能正确的访问this实例
Parenet.call(this,num);
}
-
代理模式
概念——可自定义控制对元对象的访问方式,并且允许在更新前后做一些额外处理
场景——监控,代理工具,前端框架实现
// TODO:手写proxy代理
-
迭代器模式
概念——在不暴漏数据类型的情况下访问集合中的数据;
场景——for-of遍历
自定义一个迭代器
class Counter {
constructor(limit) {
this.limit = limit;
}
[Symbol.iterator](){
let count = 1, limit = this.limit;
return {
next() {
if(count<=limit) {
return {done: false, value: count++};
} else {
return {done: true, value:undefined};
}
}
}
}
}
let conut = new Counter(3);
for(let i of count){
console.log(i)
}
-
前端框架中的设计模式
-
代理模式
场景——虚拟dom
-
组合模式
概念——可多个对象组合使用,可单个对象独立使用
场景——前端组件