这样是不是就实现了单例模式?
发布于 6 年前 作者 gwyy 3203 次浏览 来自 问答

class test {

constructor() {
    this.gwyy = "default";
}

setGwyy(gwyy) {
    this.gwyy = gwyy;
}

getGwyy() {
    return this.gwyy;
}

}

module.exports = new test();

外部输出直接是一个new的对象 这样别人require的话 应该都是这一份对象吧

4 回复

你可以看一下java的单例,饱汉模式和饿汉模式,这样的写法不是很正确。

@burning0xb 我这种算是饱汉模式

这种写法还是有办法搞出多个对象的,删掉test模块的缓存,重新require就是一个新对象了 test.js

class test {
	constructor() {
		this.gwyy = "default";
	}

	setGwyy(gwyy) {
		this.gwyy = gwyy;
	}

	getGwyy() {
		return this.gwyy;
	}
}
module.exports = new test();

解法

const obj1 = require('./test');
delete require.cache[Object.keys(require.cache).find(e => e.endsWith('test.js'))];
const obj2 = require('./test');
console.log(obj1 === obj2); // false
回到顶部