Skip to content

Commit 3dc74b0

Browse files
committed
✨ Singleton
1 parent fb791c4 commit 3dc74b0

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/creational/singleton/Sample-3.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
const Cat = (function() {
22
let instance
33
return function() {
4-
if (typeof instance !== 'object') {
4+
if (!instance) {
55
instance = this
66
}
77
return instance
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
// 用代理实现单例模式
2+
3+
function Cat() {}
4+
5+
const ProxyCat = (function() {
6+
let instance
7+
return function() {
8+
if (!instance) {
9+
instance = new Cat()
10+
}
11+
return instance
12+
}
13+
})()
14+
15+
/*============== 测试代码 ===============*/
16+
const cat1 = new ProxyCat()
17+
const cat2 = new ProxyCat()
18+
console.log(cat1 === cat2) // true

0 commit comments

Comments
 (0)