https://thebook.io/080326/0012/
질문 모음
1. 팩토리 패턴 의미
2. 팩토리 패턴 구현
3. 팩토리 패턴의 장점
4. 팩토리 패턴 이용되는 곳
5. 팩토리 패턴의 단점
객체를 사용하는 코드에서 객체 생성 부분을 떼어내 추상화한 패턴이자 상속 관계에 있는 두 클래스에서 상위 클래스가 중요한 뼈대를 결정하고, 하위 클래스에서 객체 생성에 관한 구체적인 내용을 결정하는 패턴
간단히 하면, 객체 생성 역할을 별도의 클래스에게 위임하는 것
GoF 디자인패턴에 따르면 팩토리 패턴은 두가지가 있다Factory Method
&Abstract Factory
여기서는 Factory Method
로, GoF 분류에서는 생성
및 클래스
에 해당된다. 클래스 패턴은 클래스와 서브클래스 간의 관련성을 다루며, 주로 상속을 통해 관련된다.
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 Latte(price);
else if ("Americano".equalsIgnoreCase(type)) return new Americano(price);
else return new DefaultCoffee();
}
}
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(latte);
System.out.println(ame);
}
}
// Hi this coffee is 4000
// Hi this coffee is 3000
구현을 보면 CoffeeFactory
의 상위 클래스가 뼈대를 결정하고, Latte
의 하위 클래스가 구체적인 내용을 결정
생성하는 클래스 (Latte, Americano)를 따로 만들고, 지금 Coffee를 상속받고 있고 그 안에 getPrice()
가 있기 때문에, 그에 대해 정의를 해줘야한다.
기능 추가가 많은 곳.
또한 객체 생성의 책임을 서브클래스에 위임시키고, 서브클래스에 대한 정보를 은닉하고자 할때 이용할 수 있다
구현 코드를 보면 알 수 있다. 많은 클래스를 정의해야하기 때문에 코드가 길다.