Overview

상속을 통해 슈퍼클래스의 기능을 확장하는 가장 대표적인 방법. 변하지 않는 기능은 슈퍼클래스에서 만들어지고 자주 변경되며, 확장할 기능은 서브클래스에서 만들어집니다.

추상 클래스인 AbstractClass는 실제로 실행을 위해 호출되는 public 메소드인 templateMethod로 정의되며, TemplateMethod에서 method1()과 method2()의 단계로 추상 메소드가 호출된다. 이러한 추상 메소드는 abstractClass를 상속받아 구현된 concreteClass에 정의되어 있습니다.

 

Structure

https://ko.wikipedia.org/wiki/%ED%85%9C%ED%94%8C%EB%A6%BF_%EB%A9%94%EC%86%8C%EB%93%9C_%ED%8C%A8%ED%84%B4

 

Code Example

package com.example.design.pattern;

abstract class CaffeineBeverage {
	private String userInput;

	final void prepareRecipe() {
		boilWater();
		brew();
		pourInCup();
		if (customerWantsCondiments()) {
			addCondiments();
		}
	}

	abstract void addCondiments();

	public void pourInCup() {
		System.out.println("Pouring into cup");
	}

	abstract void brew();

	public void boilWater() {
		System.out.println("Boiling water");
	}

	public boolean customerWantsCondiments() {
		String answer = getUserInput();
		if (answer.toLowerCase().startsWith("y"))
			return true;
		else
			return false;
	}

	private String getUserInput() {
		return userInput;
	}

	void setUserInput(String userInput) {
		this.userInput = userInput;
	}
}

class Coffee extends CaffeineBeverage {
	String userInput = "";

	@Override
	void addCondiments() {
		System.out.println("Adding Sugar and Milk");
	}

	@Override
	void brew() {
		System.out.println("Dripping Coffe through filter");
	}
}

class Tea extends CaffeineBeverage {
	String userInput = "";

	@Override
	void addCondiments() {
		System.out.println("Adding Lemon");
	}

	@Override
	void brew() {
		System.out.println("Steeping the tea");
	}
}

public class MyTemplateMethod {
	public static void main(String[] args) {
		CaffeineBeverage coffee = new Coffee();
		coffee.setUserInput("y");
		coffee.prepareRecipe();
		
		System.out.println("<< Next >>");
		
		CaffeineBeverage tea = new Tea();
		tea.setUserInput("n");
		tea.prepareRecipe();
	}
}

 

Console Result

Boiling water
Dripping Coffe through filter
Pouring into cup
Adding Sugar and Milk
<< Next >>
Boiling water
Steeping the tea
Pouring into cup

 

Conclusion

N/A

728x90

+ Recent posts