서론에 이어 이제 본격적으로 개별 패턴의 특징을 하나씩 살펴보자.
1. Singleton Pattern
- 애플리케이션 전체에서 단일 인스턴스를 공유
- 클래스를 한 번만 인스턴스화하고, 이 인스턴스를 전역적으로 접근해서 사용한다.
- Object.freeze() 메소드를 사용해 객체를 사용하는 쪽에서 직접 객체를 수정할 수 없도록 한다.
장점
- 메모리 공간 절약
단점
- 자바스크립트에서는 전역 변수를 생성하는 것을 흔히 안티 패턴으로 여긴다. 만약 전역 변수가 잘못된 판단으로 올바르지 않게 만들어진 경우 잘못된 값으로 덮어쓰여질 수 있으며, 이 변수를 참조하는 구현들이 모두 예외를 발생시킬 수 있기 때문이다.
- 그러나 Singleton 패턴은 일반적으로 앱에 전역 상태를 위해 사용한다. 코드의 여러 부분에서 수정 가능한 하나의 객체를 직접 접근하도록 설계하면 예외가 발생하기 쉬워진다. 보통 어떤 코드들은 데이터를 읽어들이는 부분을 위해 전역 상태를 수정하기도 한다. 이 경우 실행 순서가 중요해진다. 데이터가 만들어지지 않았는데 사용할 수는 없기 때문이다.
예제 코드 1) Config
class Config {
constructor() {}
start() { console.log("App has started.") }
update() { console.log("App has updated.") }
}
const instance = new Config()
Object.freeze(instance)
예제 코드 2) ToastMessage
function ToastMessage() {
if (ToastMessage.instance) {
return ToastMessage.instance;
}
this.basePhrase = "Message Toast: ";
ToastMessage.instance = this;
}
ToastMessage.prototype.toastMessage = function (message, type) {
const { background, color } = this.getColorToast(type);
return console.log(
`%c${this.basePhrase + message}`,
`background: ${background}; color: ${color}`
);
};
ToastMessage.prototype.getColorToast = function (type) {
switch (type) {
case "error":
return {
background: "black",
color: "red",
};
case "warning":
return {
background: "transparent",
color: "orange",
};
default:
return {
background: "black",
color: "green",
};
}
};
const toastMessageErrorInstance = new ToastMessage();
const toastMessageAcceptedInstance = new ToastMessage();
console.log(
"is it equal?",
toastMessageErrorInstance === toastMessageAcceptedInstance
);
toastMessageErrorInstance.toastMessage("Sending message failed", "error");
toastMessageAcceptedInstance.toastMessage("Message send", "accepted");
사족: 위의 예제에서는 인스턴스를 생성하고 사용하는 과정보다 아래와 같이 브라우저 콘솔창에 다양한 색깔로 메시지가 출력된다는 게 신기했다. 👀 이 외에도 console.log()를 다양하게 활용하는 방법에 대해 잘 정리한 포스팅은 여기를 참조하면 좋다.
스터디에서 논의했던 부분
axios.create()로 인스턴스를 생성한 후, 이 인스턴스를 앱 전역에서 사용하는 아래의 코드 패턴을 싱글턴 패턴이라고 볼 수 있을지에 대해 얘기를 나누었고, '그렇다'라고 결론을 내렸다.
📚 참고자료
'배워서 남 주자' 카테고리의 다른 글
디자인 패턴 - Factory 패턴 (0) | 2023.10.15 |
---|---|
디자인 패턴 - Prototype 패턴 (0) | 2023.10.11 |
디자인 패턴 - introduction (1) | 2023.10.08 |
innerText, textContent, innerHTML의 차이 (0) | 2023.09.24 |
VS code에서 carbon처럼 코드를 예쁘게 캡처할 수 있는 extension (0) | 2023.09.09 |