팩토리 메서드 패턴 (Factory Method)
팩토리 메서드 패턴(Factory Method Pattern)은 객체 생성을 직접 하지 않고, 생성을 담당하는 공장(Factory) 클래스에 위임하는 패턴입니다.
게임에서 유닛을 생성할 때 new Marine()을 직접 호출하면 클래스간의 결합도가 심하게 높아집니다. 대신 UnitFactory.create("Marine") 처럼 문자열이나 열거형을 넘기면 알아서 적절한 객체를 튀어나오게 만들어, 향후 새로운 유닛이 추가되더라도 기존 코드를 수정할 필요가 없도록 만듭니다.
// Product
interface Weapon {
void attack();
}
class Sword implements Weapon {
public void attack() { System.out.println("검으로 베기!"); }
}
class Bow implements Weapon {
public void attack() { System.out.println("활쏘기!"); }
}
// Creator
abstract class Blacksmith {
// 팩토리 메서드
public abstract Weapon craftWeapon();
public void testWeapon() {
Weapon weapon = craftWeapon();
weapon.attack();
}
}
class SwordBlacksmith extends Blacksmith {
public Weapon craftWeapon() { return new Sword(); }
}
class BowBlacksmith extends Blacksmith {
public Weapon craftWeapon() { return new Bow(); }
}
public class Main {
public static void main(String[] args) {
Blacksmith smith1 = new SwordBlacksmith();
smith1.testWeapon(); // 검으로 베기!
Blacksmith smith2 = new BowBlacksmith();
smith2.testWeapon(); // 활쏘기!
}
}