Notice
Recent Posts
Recent Comments
Link
«   2025/08   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Tags
more
Archives
Today
Total
관리 메뉴

mooni

[Design Pattern] 팩토리 패턴(Factory Pattern) 본문

etc.

[Design Pattern] 팩토리 패턴(Factory Pattern)

mooni_ 2025. 4. 5. 16:21

팩토리 패턴(Factory Pattern) : 객체 생성 로직을 캡슐화하여, 클라이언트 코드가 구체적인 클래스에 직접 의존하지 않도록 도와주는 패턴

  • 상위 클래스와 하위 클래스가 분리되기 때문에 느슨한 결합을 가짐
  • 상위 클래스에서는 인스턴스 생성 방식에 대해 전혀 알 필요가 없어서 많은 유연성을 갖게 됨
  • 유지 보수성 증가

 

EX) JavaScript에서의 Factory

class CoffeeFactory {
    static createCoffee(type) {
        const factory = factoryList[type]
        return factory.createCoffee()
    }
}

class Latte {
    constructor() {
        this.name = "latte"
    }
}

class Espresson {
    constructor() {
        this.name = "espresson"
    }
}

class LatteFactory extends CoffeeFactory {
    static createCoffee() {
        return new Latte()
    }
}

class EspressonFactory extends CoffeeFactory {
    static createCoffee() {
        return new Espresso()
    }
}

const factoryList = { LatteFactory, EspressonFactory }

const main = () => {
    const coffee = CoffeeFactory.createOcffee("LatteFactory")
    console.log(coffee.name)
}

main()
  • CoffeeFactory : 중요한 뼈대 역할
  • LatteFactory, EspressonFactory : 구체적인 내용 결정
  • 하위 클래스에서 생성한 인스턴스를 상위 클래스에 의존성 주입을 하고 있음

 

EX) Java에서의 Factory

enum CoffeeType {
    LATTE,
    ESPRESSO
}

abstract class Coffee {
    protected String name;
    
    public String getName() {
        return name;
    }
}

class Latte extends Coffee {
    public Lattee() {
        name = "latte";
    }
}

class Espresso extends Coffee {
    public Espresso() {
        name = "expresso";
    }
}

class CoffeeFactory {
    public static Coffee createCoffee(CoffeeType type) {
        switch(type) {
            case LATTE :
                return new Latte();
            case ESPRESSO :
                return new Espresso();
            default :
                throw new IllegalArgumentException("Invalid coffee type: " + type);
        }
    }
}

public class Main {
    public static void main(String[] args) {
        Coffee coffee = CoffeeFactory.createCoffee(CoffeeType.LATTE);
        System.out.println(coffee.getName());
    }
}
  • CoffeeFactory 밑에 Coffee 클래스를 놓고 해당 클래스를 상속하는 Latte, Espresso 클래스 구현

 

싱글톤 패턴 vs 팩토리 패턴

항목 Singleton Pattern Factory Pattern
목적 단 하나의 인스턴스 보장 다양한 인스턴스를 생성하고 관리
생성 시점 최초 접근 시 요청이 있을 때마다
테스트 용이성 전역 상태로 인해 어려움 의존성 주입 및 모킹 쉬움
유연성 낮음 (클래스 고정) 높음 (생성 전략 유연하게 변경 가능)