[면접을 위한 CS 전공지식 노트] 디자인 패턴 - 팩토리 패턴

Yijun Jeon·2023년 12월 28일
0

CS 전공지식

목록 보기
2/21
post-thumbnail

디자인 패턴

💡 디자인 패턴이란?

  • 프로그램을 설계할 때 발생했던 문제점들을 객체 간의 상호 관계 등을 이용하여 해결할 수 있도록 하나의 '규약' 형태로 만들어 놓은 것

팩토리 패턴

💡 팩토리 패턴 (factory pattern) 이란?

  • 객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴
  • 상속 관계에서 상위 클래스가 중요한 뼈대를 결정, 하위 클래스에서 객체 생성에 관한 구체적인 내용 결정
    • 두 클래스 분리 -> 느슨한 결합
    • 상위 클래스 -> 더 많은 유연성 (생성 방식 몰라도 됨)
    • 유지 보수성 증가

🔗 자바스크립트 팩토리 패턴
👉 자바스크립스의 new Object로 전달받은 값에 따라 다른 객체 생성

const num = new Object(42)
const str = new Object('abc')
num.constructor.name; // Number
num.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 CoffeeFactory{
	static createCoffee(type){
		const factory = factoryList[type]
		return factory.createCoffee()
	}
}

const main = () => {
	// 라떼 커피를 주문
	const coffee = CoffeeFactory.createCoffee("LatteFactory")
	// 커피 이름을 부름
	console.log(coffee.name) // latte
}
  • LatteFactory에서 생성한 인스턴스를 CoffeeFactory에서 주입하기 때문에 의존성 주입으로도 볼 수 있음
  • static 정적 메서드 -> 객체를 만들지 않고도 호출 가능, 메모리 할당 한 번만 실행

🔗 팩토리 패턴 활용 자바 예시 코드

abstract class Coffee{
	public abstract int getPrice();

	@Override
	public String toString(){
		return "Hi this coffee is " + this.getPrice();
	}
}

class CoffeeFactory{
	public static Coffee getCoffee(String type, int price){
		if("Latte".equalsIgnore(type)) return new Latte(price);
		else if("Americano".equalsIgnore(type)) return new Americano(price);
		else return new DefaultCoffee();
	}
}

0개의 댓글