[CS]:: Design pattern - 팩토리패턴 factory pattern

김종건·2023년 5월 15일

CS 디자인 패턴

목록 보기
2/8
post-thumbnail

🎯팩토리 패턴

객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴이자 상속관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴이다


class CoffeeFactory {
  static createCoffee(type) {
      const factory = factoryList[type]
      return factory.createCoffee()
  }
}
class Latte {
  constructor() {
      this.name = "latte"
  }
}
class Espresso {
  constructor() {
      this.name = "Espresso"
  }
}

class LatteFactory extends CoffeeFactory{
  static createCoffee() {
      return new Latte()
  }
}
class EspressoFactory extends CoffeeFactory{
  static createCoffee() {
      return new Espresso()
  }
}
const factoryList = { LatteFactory, EspressoFactory }


const main = () => {
  // 라떼 커피를 주문한다.
  const coffee = CoffeeFactory.createCoffee("LatteFactory")
  // 커피 이름을 부른다.
  console.log(coffee.name) // latte
}
main()
  • CoffeeFactory 는 뼈대라면 LatteFactory , EspressoFactory 가 구체적인 내용을 결정하고 있다

    유연성 있다

    유지보수성 증가

    비슷한 객체를 반복적으로 생성해야 할 경우 사용하는 패턴

    객체를 생산하는 공장(Factory)을 구현하는 방법

    참고

    개발자가 알아야할 디자인패턴
    https://github.com/wnghdcjfe/csnote

  • profile
    https://github.com/Foccy https://foccy-github-5er7huis0-foccy.vercel.app/?category=category1

    0개의 댓글