"아직 부족한 저는 제가 이해한 대로 최대한 쉽게 적고 있습니다."
생성 패턴
디자인 패턴은 생성, 구조, 행위로 나뉩니다.
그 중에서 생성 패턴 을 알아보고 있습니다..
생성 패턴
이란 클래스가 인스턴스를 생성하는 과정을 디자인한 패턴 입니다.
오늘의 두 번째 패턴은 팩토리 메서드 패턴
입니다.
팩토리 메서드 패턴
자식 클래스들의 생성자들을 묶어서 생성하는 클래스와 인스턴스
(싱글톤 패턴 다음으로 팩토리 패턴을 선택한 것은 실수다.
이해하는 데 시간이 조금 걸렸다...)
이미 작성된 포스트들도 꾸준히 리뉴얼할수 있도록 하겠습니다!
팩토리 메서드 패턴은 constructor 생성가 아닌
" 생성하는 방법을 담당하는 " 클래스를 제작하는 것이다.
class Button {
constructor(content){
this.content = content,
this.action = () => console.log("The button was pressed.")
}
}
class Text {
constructor(content){
this.content = content,
this.action = () => console.log("Please enter your text")
}
}
class Component {
constructor(type,content){
if(type == "button")
return new Button(content)
if(type == "text")
return new Text(content)
}
}
const LogInButton = new Component("button","Login")
const titleText = new Component("text","myTitle")
아래의 두 줄과 같이 생성하는 과정이 깔끔해지는 것을 직관적으로 알 수 있게 작성하였습니다.