# 单例模式

一个类只有一个实例,并提供一个访问它的全局访问点。

class Suporka {
    constructor() {
        this.name = 'Suporka'
    }
    eat() {
        console.log('suporka is eating')
    }
    sleep() {
        console.log('suporka is sleeping')
    }
}
Suporka.getInstance = (function () {
     let instance
     return function () {
        if (!instance) {
            instance = new Suporka()
        }
        return instance
     }
 })()

let userOne = Suporka.getInstance()
userOne.eat()

let userTwo = Suporka.getInstance()
userTwo.sleep()

console.log(userOne === userTwo)
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