← 返回首页
Nodejs实现单例模式
发表时间:2023-06-14 08:28:24
Nodejs实现单例模式

1.Nodejs实现单例模式


class Dog{
    constructor() {
       console.log(' a Dog is created...')
    }
}

class Human{
    constructor() {
        console.log(' a Human is created...')
    }
}

const createSingletonUtil = (className) => {
    let instance;
    return () => {
        return (instance ??= new className());
    };
};

let getSingletonClass = createSingletonUtil(Human);
let obj1 = getSingletonClass();
let obj2 = getSingletonClass();

console.log(obj1 === obj2);

getSingletonClass = createSingletonUtil(Dog);
obj1 = getSingletonClass();
obj2 = getSingletonClass();

console.log(obj1 === obj2);

注意:使用??= 运算符, 必须在Nodejs 18+版本以上。

运行结果:

 a Human is created...
true
 a Dog is created...
true