템플릿 메서드 패턴(Template Method Pattern)은 전체적인 알고리즘의 '뼈대(흐름)'는 부모(추상) 클래스에 정의하고, 단계별 '구체적인 구현'은 자식 클래스에게 위임하는 행위 패턴입니다.
커피와 홍차를 끓이는 과정을 보면 `1. 물 끓이기 -> 2. 우려내기 -> 3. 컵에 따르기 -> 4. 첨가물 넣기` 로 전체 흐름이 완벽히 똑같습니다. 이때 부모 클래스의 makeBeverage() 메서드 안에 이 4단계의 순서를 고정(final)해두고, 자식 클래스(Coffee, Tea)는 2번과 4번 내용만 알맞게 오버라이딩하여 코드 중복을 완전히 제거합니다.
📐 Template Method Pattern UML
템플릿 메서드 패턴은 알고리즘의 골격을 정의하고 일부 단계를 서브클래스로 연기합니다.
class BeverageRecipe {
prepareRecipe() {
this.boilWater();
this.brew();
this.pourInCup();
this.addCondiments();
}
boilWater() { console.log("물 끓이는 중"); }
pourInCup() { console.log("컵에 따르는 중"); }
brew() { throw new Error("추상 메서드: brew 구현 필요"); }
addCondiments() { throw new Error("추상 메서드: addCondiments 구현 필요"); }
}
class Tea extends BeverageRecipe {
brew() { console.log("찻잎 우려내는 중"); }
addCondiments() { console.log("레몬 추가"); }
}
class Coffee extends BeverageRecipe {
brew() { console.log("커피 내리는 중"); }
addCondiments() { console.log("설탕과 우유 추가"); }
}
console.log("--- 차 준비 ---");
new Tea().prepareRecipe();
console.log("\n--- 커피 준비 ---");
new Coffee().prepareRecipe();