1、单例模式

核心:确保一个类只有一个实例,并提供一个全局访问点
场景:状态管理、路由对象都是只有一个实例的

代码实现:
普通版本

1
2
3
4
5
6
7
8
9
10
11
12
function Father(name) {
if(Father.instance) return Father.instance

this.name = name

Father.instance = this
}

const f1 = new Father('xx')
const f2 = new Father('yy')

f1 === f2 // true

友好版本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const createSingle = function(fn) {
let instance;

return function(...args) {
return instance || (instance = new fn(...args))
}
}

function Father(name, age) {
this.name = name
this.age = age
}

const createSingleFather = createSingle(Father)

const f1 = new createSingleFather('xx', 45)
const f2 = createSingleFather('yy', 49)

f1 === f2 // true

总结:多次调用函数,想办法永远只产生一个实例就行


1、单例模式
https://mrhzq.github.io/职业上一二事/前端面试/JS 设计模式/1、单例模式/
作者
黄智强
发布于
2024年2月13日
许可协议