// 1. Define interface
interface Animal {
void speak();
}
// 2. Implement concrete classes
class Dog implements Animal {
@Override
public void speak() {
System.out.println("멍멍!");
}
}
class Cat implements Animal {
@Override
public void speak() {
System.out.println("야옹!");
}
}
// 3. Factory class
class AnimalFactory {
public static Animal createAnimal(String type) {
if (type.equalsIgnoreCase("dog")) {
return new Dog();
} else if (type.equalsIgnoreCase("cat")) {
return new Cat();
}
throw new IllegalArgumentException("Unknown animal type: " + type);
}
}
// 4. Usage example
public class Main {
public static void main(String[] args) {
Animal dog = AnimalFactory.createAnimal("dog");
dog.speak(); // Output: 멍멍!
Animal cat = AnimalFactory.createAnimal("cat");
cat.speak(); // Output: 야옹!
}
}
팩토리 패턴은 객체 생성 과정이 복잡하거나, 객체 유형에 따라 다른 클래스가 생성될 필요가 있을 때 유용합니다. 몇 가지 대표적인 상황은 다음과 같습니다:
요약하면, 팩토리 패턴은 “객체 생성 로직이 복잡하거나 유연성이 요구될 때” 사용하면 좋습니다.