본문 바로가기
CS/디자인패턴

[CS] 팩토리 패턴

by Johnny's 2023. 9. 1.

팩토리 패턴?

팩토리 패턴이란 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴

 

장점

상위 클래스에서는 객체 생성방식에 대해 알 필요가 없어져 유연성을 가짐
객체 생성 로직은 하위 클래스에서만 관리 되기 때문에 유지 보수성이 증가
상위 클래스와 하위 클래스가 분리되기 때문에 로직 관리하기가 편함

 

js

// 상위 클래스
class CoffeeFactory {
    // static - 정적메서드
    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();

 

java

enum CoffeeType {
    LATTE,
    ESPRESSO
}

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

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

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

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()); // latte
    }
}

 

* 참고

- CS 지식의 정석 | 디자인패턴 네트워크 운영체제 데이터베이스 자료구조 -인프런

댓글