자바스크립트의 팩토리 패턴

    자바스크립트에서 팩토리 패턴을 구현한다면 간단하게 new Object()로 구현할 수 있습니다.

     

    자바스크립트

    const num = new Object(42)
    const str = new Object('abc')
    num.constructor.name; // Number
    str.constructor.name; // String

    숫자를 전달하거나 문자열을 전달함에 따라 다른 타입의 객체를 생성하는 것을 볼 수 있습니다. 즉, 전달받은 값에 따라 다른 객체를 생성하며 인스턴스의 타입 등을 정합니다.

    커피 팩토리를 기반으로 라떼 등을 생산하는 코드를 구축해보겠습니다.

     

    자바스크립트

    코드 위치: ch1/5.js

    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
    }
    main()
    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.