// 싱글톤이 아닌 경우 두 인스턴스가 다름 classNotSingleton{
constructor(a) {
this.value = a;
}
}
const a = new NotSingleton(1);
const b = new NotSingleton(1);
console.log(a === b) // false
// 싱글톤인 경우 인스턴스를 공유함classSingleton() {
constructor() {
if (!Singleton.instance) { // 인스턴스 미생성시 생성
Singleton.instance = this;
}
return Singleton.instance; // 기존 인스턴스 반환
}
getInstance() {
returnthis;
}
}
const a = new NotSingleton();
const b = new NotSingleton();
console.log(a === b) // true
DB 연결 모듈 예제
const URL = "mongodb://localhost:";
const createConnection = url => ({"url" : url});
classDB{
constructor(url) {
if (!DB.instance) {
DB.instance = createConnection(url);
}
return DB.instance; // 기존 DB 인스턴스를 반환
}
connect() {
returnthis.instance;
}
}
const a = new DB(URL);
const b = new DB(URL);
console.log(a === b); // true
싱글톤 패턴의 단점 예제
mocha.js 를 이용한 TDD 시 각 test가 독립적이지 않음
const assert = require('assert');
const a = [1, 2, 3]
describe('Array', function () {
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(a.indexOf(4), -1);
a[0] = 4; // 여기 때문에 테스트에 영향을 끼침
});
});
describe('#indexOf()', function () {
it('should return -1 when the value is not present', function () {
assert.equal(a.indexOf(4), -1);
});
});
});
// 결과 // 1 passing// 1 failing
전역에 있는 a를 수정하면서 테스트에 영향을 미치게 되는데 a를 인스턴스라고 하면 각 테스트가 서로 영향을 주게 됨