본문 바로가기

Trouble Shooting

자바스크립트, 싱글톤(Singleton) 객체 만들기

문득 자바스크립트 'class'선언을 이용할 때 싱글톤 객체를 만들어 보고 싶었다. 더 좋은 방법이 있는지 모르겠지만, 두가지 방법이 떠올라 테스트해 보았다.


첫번째 방법

외부의 const로 선언한 변수를 이용하는 방법인데... 조금은 거슬리는 느낌...

class TestSingletone

{

static get instance() { return __TestSingletoneInstance; }


hello()

{

console.log("Hello World!");

}

}

const __TestSingletoneInstance = new TestSingletone;


테스트/사용 코드는 아래에 있다. 동작은 잘 되는 것 같다. 다만 클래스 바깥에 코드가 있어야 되는 점이 거슬린다.

TestSingletone.instance.hello();


try

{

// 상수값을 재정의 하는 아래 코드에서 예외가 발생한다.

__TestSingletoneInstance = new TestSingletone;

}

catch(e)

{

console.error(e.message, e);

}



두번째 방법

'window'객체를 살짝 이용하는 방식인데... 이 또한 조금은 거슬린다. 그러나 모든 코드를 객체내에 위치 시킬 수 있다. 이 방식이 첫번째 보다는 나은 것 같다. 그리고 'window'객체를 대체하는 것을 고안한다면 더욱 완벽한 방식이 될 것 같다.


class TestOther

{

static get instance()

{

if ( window.__OtherInstance == undefined )

{

const __instance = new TestOther;

window.__OtherInstance = __instance;

}


return window.__OtherInstance;

}


hello()

{

console.log("Hello World!");

}

}


두번째 방식의 테스트/사용 코드는 아래에...

TestOther.instance.hello();


try

{

// 아래코드에서 정확히 예외가 발생한다. 

TestOther.instance = new TestOther;

}

catch(e)

{

console.error(e.message, e);

}


마치며

첫번째, 두번째 모두 무난히 사용할 수 있는 방법이라고 생각한다. 그리고 두번째 방식에서 'window'객체 대신에 외부로 최대한 노출이 되지 않는 전역 객체를 고안해서 사용한다면, 더욱 정교하게 자바와 유사한 싱글톤 객체를 만들 수 있다고 본다.


그러나 보통 싱글톤 객체는 생성자를 외부에서 호출될 수 없어야 하는데, 그렇게 하지 못했으므로 절반의 싱글톤 방식이라 생각한다.