디자인패턴이란 프로그램 설계시 발생한 문제점들을 객체 간의 상호 관계 등을 이용하여 해결할 수 있도록 하나의
규약형태로 만들어 놓은 것을 의미한다
반복적으로 일어나는 문제점들을 어떻게 해결해나갈 것인가에 대한 일종의솔루션
하나의 클래스에 하나의 인스턴스
- 클래스 - 객체를 정의하는 틀 (설계도)
- 인스턴스 - 클래스로부터 선언된 객체 (Object)
리터럴 {} 혹은 new Object()로 객체를 생성, 이 자체만으로 어떤 객체와도 같지 않기때문에 싱글톤 패턴을 구현할 수 있다
class Singleton { constructor() { // constructor는 객채를 생성하고 초기화하는 메서드 if(!Singleton.instance) { Singleton.instance = this; // this는 Singleton 클래스에서 생성된 인스턴스 객체를 나타냄 } return Singleton.instance; } } const a = new Singleton(); const b = new Singleton(); console.log(a === b); // true
- 데이터베이스 연결 모듈에 많이 쓰임
const createConnection = url => ({
'url' : url
});
class DB {
constructor(db_url) {
if(!DB.instance) {
DB.instance = createConnection(db_url); // {"url" : db_url }
}
return DB.instance;
}
connect() { // 메서드
return DB.instance
}
}
const a = new DB(URL);
const b = new DB(URL);
conosole.log(a === b); true
URL은 URL객체를 말하며, 해당 URL객체 속성으로는hash,host,hostname,href,origin,pathname,port,protocol,search,searchParams,username등이 있으며 메서드로는toString(),toJSON(), 정적메서드인createObjectURL(),revokeObjectURL()등이 있다.
의존성주입이란 메인모듈이 하위모듈에 직접 의존성을 주기보다는, 중간에 의존성주입자를 넣어 간접적으로 의존성을 주입하는 방식입니다
팩토리패턴이란 객체 생성 부분을 떼어내 추상화한 패턴이며, 상위클래스는 중요한 뼈대를, 하위클래스는 객체 생성의 구체적인 내용을 결정한다
const num = new Object(42);
const str = new Object('abc');
num.constructor.name; // Number
str.constructor.name; // String
class Latte {
constructor(){
this.name = 'latte'
}
}
class Espresso {
constructor(){
this.name = 'espresso'
}
}
class LatteFactory {
static createCoffee(){
return new Latte()
}
}
class EspressoFactory {
static createCoffee(){
return new Espresso();
}
}
const factoryList = { LatteFactory, EspressoFactory }
class CoffeFactory {
static createCoffee(type){
const factory = factoroyList[type];
return factory.createCoffee();
}
}
const main = () => {
const coffee = CoffeFactory.createCoffee("LatteFactory");
console.log(coffe.name)
}