Templat Method Pattern은 알고리즘의 뼈대를 메소드 내에 정의하고, 일부 단계는 서브클래스에서 구현하도록 연기한다.
Template Method Pattern은 알고리즘의 구조를 변경하지 않고, 서브클래스에서 특정 단계를 재정의할 수 있게 한다.
커피와 차를 제작할 때에는 공통 작업과 개별 작업이 있다.
1. 물 끓이기 (공통)
2. 커피 내리기 / 차 우려내기 (개별)
3. 컵에 따르기(공통)
4. 설탕이나 우유 넣기 / 레몬 넣기 (개별)
Coffee와 Tea 클래스에서 각각 prepareRecipe 메소드를 위 1~4에 맞게 정의하여 해당 음료를 제작할 수 있다.
다른 방법으로는 CaffeineBeverage 클래스를 정의하고, prepareRecipe, boilWater, pourInCup 메소드를 선언한다.
다음으로, 각각의 음료는 CaffeineBeverage 클래스를 상속받고 각자의 작업을 별도 메소드로 정의하면 된다.
하지만 2,4번에서 한번 더 공통의 메소드로 추출해낼 수 있다.
CaffeineBeverage 클래스를 추상 클래스로 변경하고, 음료 각각의 작업 또한 brew, addCondiments 메소드로 생성한다.
각 음료에서 각각의 작업에 맞게 위 메소드를 정의해주면 된다.
public abstract class CaffeineBeverage {
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
public void boilWater() {
System.out.println("Boiling water");
}
public abstract void brew();
public void pourInCup() {
System.out.println("Pouring into cup");
}
public abstract void addCondiments();
}
public class Coffee extends CaffeineBeverage{
@Override
public void brew() {
System.out.println("Brewing coffee");
}
@Override
public void addCondiments() {
System.out.println("Adding sugar");
}
}
public class Tea extends CaffeineBeverage {
@Override
public void brew() {
System.out.println("Steeping the tea");
}
@Override
public void addCondiments() {
System.out.println("Adding Lemon");
}
}
public class TemplateSimulation {
public static void main(String[] args) {
Coffee coffee = new Coffee();
Tea tea = new Tea();
coffee.prepareRecipe();
System.out.println();
tea.prepareRecipe();
}
}

Design Principle
The Hollywood Principle: Don't call us, we'll call you
=> high-level components가 필요할 때마다 low-level components를 호출하고, low-level components는 호출될 때까지 대기한다.
high-level component: CaffeineBevarage
low-level component: Coffee, Tea
CaffeineBeverage가 필요할 때마다 Coffe와 Tea를 호출하고, Coffee와 Tea는 단지 대기할 뿐이다.
'공부 > 디자인 패턴' 카테고리의 다른 글
| 7-1. Adapter Pattern (Head First Design Pattern) (0) | 2024.10.25 |
|---|---|
| 6. Command Pattern (Head First Design Patterns) (0) | 2024.10.25 |
| 5. Singleton Pattern (Head First Design Patterns) (0) | 2024.10.22 |
| 4. Factory Pattern (Head First Design Patterns) (0) | 2024.10.22 |
| 3. Decorator Pattern (Head First Design Patterns) (0) | 2024.10.20 |