0%

单例模式

单例模式

单例模式下的类只能存在一个实例对象

非单例模式实例

在 JavaScript 中, 我们可以通过 class 类来实例化对象, 我们 new 出两个对象, 但是两个对象是没有直接关联的, 他们储存在不同的内存地址中, 不符合我们的单例模式

1
2
3
4
5
6
7
8
class Singleton {
show() {
console.log('单例对象')
}
}
const s1 = new Singleton()
const s2 = new Singleton()
s1 === s2 // false 引用类型储存在堆的不同内存地址中

单例模式实例

如果要实现单例模式, 我们需要保证只能存在一个实例对象, 这就要求我们的类具有是否已存在实例对象的功能

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// 类 - 静态方法模拟
class Singleton {
show() {
consle.log('我是一个单例对象')
}
static getInstance() {
// 静态方法 重点
if(!Singleton.instance){
// 判断是否已存在一个实例
Singleton.instance = new Singleton() // 如果没有就创建一个
}
return Singleton.instance
}
}

// 闭包实现单例模式
function Singleton(){}
Singleton.prototype.getInstance = (function(){
let instance // 定义局部变量模拟 重点
return function() {
if(!instance) {
instance = new Singleton()
}
return instance
}
})()

单例模式应用

通过单例模式管理全局唯一存在的一个 Model 模态框

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<style>
div {
width: 200px;
height: 200px;
line-height: 200px;
border: 1px solid pink;
color: pink;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
</style>
<title>Document</title>
</head>
<body>
<button id="show">显示全局模拟框</button>
<button id="hidden">隐藏全局模拟框</button>
<script>
window.onload = function() {
let showbtn = document.getElementById('show')
let hiddenbtn = document.getElementById('hidden')

// 闭包实现
const Modal = (function() {
let modal = null
return function() {
if (!modal) {
modal = document.createElement('div')
modal.innerText = '我一个单例的模态框'
modal.style.display = 'none'
modal.style.color = 'pink'
document.body.appendChild(modal)
}
return modal
}
})()

showbtn.addEventListener(
'click',
function() {
const modal = new Modal()
modal.style.display = 'block'
},
false
)

hiddenbtn.addEventListener(
'click',
function() {
const modal = new Modal()
modal.style.display = 'none'
},
false
)
}
</script>
</body>
</html>
请作者喝杯咖啡