TIL/CS

[디자인패턴] 싱글톤 패턴

에리조나진생 2024. 5. 16. 22:48

싱글톤 패턴

싱글톤 패턴

  • 하나의 클래스에 오직 하나의 인스턴스만 가지는 패턴
  • 인스턴스 생성 시 발생하는 비용을 줄이기 위해 사용함
  • 인스턴스 생성에 많은 비용이 드는 데이터 연결모듈에 많이 쓰임
  • 의존성이 높아지고 TDD를 할 때 불편함
// 싱글톤이 아닌 경우 두 인스턴스가 다름 
class NotSingleton {
    constructor(a) {
        this.value = a;
    }
}
const a = new NotSingleton(1);
const b = new NotSingleton(1);
console.log(a === b) // false
// 싱글톤인 경우 인스턴스를 공유함
class Singleton() {
    constructor() {
        if (!Singleton.instance) { // 인스턴스 미생성시 생성 
            Singleton.instance = this;
        }
        return Singleton.instance; // 기존 인스턴스 반환 
    }
    getInstance() {
        return this;
    }
}
const a = new NotSingleton();
const b = new NotSingleton();
console.log(a === b) // true

DB 연결 모듈 예제

const URL = "mongodb://localhost:";
const createConnection = url => ({"url" : url});
class DB {
    constructor(url) {
        if (!DB.instance) {
            DB.instance = createConnection(url);
        }
        return DB.instance; // 기존 DB 인스턴스를 반환 
    }
    connect() {
        return this.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를 인스턴스라고 하면 각 테스트가 서로 영향을 주게 됨

'TIL > CS' 카테고리의 다른 글

[디자인 패턴] 프록시(Proxy) 패턴  (0) 2024.07.09
[디자인패턴] 팩토리 패턴  (0) 2024.05.17
브라우저 렌더링 과정  (0) 2024.02.03
메모리란?  (1) 2024.01.10