공부/면접을 위한 CS 전공지식 노트

[CS 스터디/디자인패턴] 3. 팩토리 패턴(Factory Pattern)

규투리 2022. 12. 14. 10:03
반응형

3.1 팩토리 패턴이란?

팩토리 패턴이란?
객체를 생성하기 위해 필요한 인터페이스를 만든 후, 인터페이스를 구현하는 클래스에서 어떤 객체를 만들지 결정하는 패턴

팩토리 패턴의 로직은 다음과 같다.

객체를 사용하는 코드에서 객체 생성 부분을 떼어내서 추상화를 한다.

또, 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하며, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정한다.

 

상위 클래스와 하위 클래스가 분리되기 때문에 느슨한 결합을 가지며, 상위 클래스에서는 인스턴스 생성 방식에 대해 전혀 알 필요가 없기 때문에 더 많은 유연성을 갖게 된다.

또한, 객체 생성 로직이 따로 분리되어 있기 때문에 코드의 유지 보수성이 증가된다.

 

// 커피 인터페이스
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".equalsIgnoreCase(type)) return new Latee(price);
    else if("Americano".equalsIgnoreCase(type)) return new Americano(price);
    else { 
    	return new BlackCoffee(); 
    }
  }
}

// 그냥 커피
Class DefaultCoffee extends Coffee {
  private int price;
  
  public DefaultCoffee() {
    this.price = -1;
  }
  
  @Override
  public int getPrice() {
    return this.price;
  }
}

// 라떼
Class Latte extends Coffee {
  private int price;
  
  public Latte(int price) {
    this.price = price;
  }
  
  @Override
  public int getPrice() {
    return this.price;
  }
}

// 아메리카노
Class Americano extends Coffee {
  private int price;
  
  public Americano(int price) {
    this.price = price;
  }
  
  @Override
  public int getPrice() {
    return this.price;
  }
}

// 커피공장에 라떼와 아메리카노를 주문한다.
public class HelloWorld {
  public static void main(String[] args) {
    Coffee latte = CoffeeFactory.getCoffee("Latte", 4000);
    Coffee ame = CoffeeFactory.getCoffee("Americano", 3000);
    System.out.println("Factory latte :: " + latte);
    System.out.println("Factory ame :: " + ame);
  }
}

/*
* Facotry Latte :: Hi this coffee is 4000
* Facotry ame :: Hi this coffee is 3000
*/
반응형