Template Method Pattern - dnwls16071/Backend_Summary GitHub Wiki
π Template Method Pattern μ€λͺ
- μ¬λ¬ ν΄λμ€μμ 곡ν΅μΌλ‘ μ¬μ©νλ λ©μλλ₯Ό ν
νλ¦ΏνμμΌμ μμ ν΄λμ€μ μΆμ ν΄λμ€λ‘ μ μνκ³ κ° νμ ν΄λμ€λ§λ€ μΈλΆ λμ μ¬νμ λ€λ₯΄κ² ꡬννλ ν¨ν΄μ΄λ€.
[Ex1]
abstract class Beverage {
// λ μνΌλ₯Ό μ€λΉνλ€.
// λ¬Ό λμ΄κΈ° -> μλ£λ₯Ό μ°λ €λ΄κΈ° -> μ»΅μ λ°λ₯΄κΈ° -> 첨κ°λ¬Ό μΆκ°νκΈ°
final void prepareRecipe() {
boilWater();
brew();
pourInCup();
addCondiments();
}
void boilWater() {
System.out.println("Boiling water");
}
void pourInCup() {
System.out.println("Pouring into cup");
}
abstract void brew();
abstract void addCondiments();
}
// ν° λ°©μ
class Tea extends Beverage {
void brew() {
System.out.println("Steeping the tea");
}
void addCondiments() {
System.out.println("Adding lemon");
}
}
// μ»€νΌ λ°©μ
class Coffee extends Beverage {
void brew() {
System.out.println("Dripping coffee through filter");
}
void addCondiments() {
System.out.println("Adding sugar and milk");
}
}
[Ex2]
abstract class DataProcessor {
// λ°μ΄ν° κ°κ³΅ νλ‘μΈμ€
public final void process(String data) {
loadData(data);
if (isValidData(data)) {
processData(data);
saveData(data);
} else {
System.out.println("Data is invalid, processing aborted.");
}
}
protected abstract void loadData(String data); // λ°μ΄ν° λ‘λ
protected abstract boolean isValidData(String data); // μ ν¨νμ§
protected abstract void processData(String data); // λ°μ΄ν° νλ‘μΈμ€
protected abstract void saveData(String data); // λ°μ΄ν° μ μ₯
}
// CSV λ°©μ
class CSVDataProcessor extends DataProcessor {
@Override
protected void loadData(String data) {
System.out.println("Loading data from CSV file: " + data);
}
@Override
protected boolean isValidData(String data) {
return data != null && data.contains("CSV");
}
@Override
protected void processData(String data) {
System.out.println("Processing CSV data");
}
@Override
protected void saveData(String data) {
System.out.println("Saving CSV data to database");
}
}
// JSON λ°©μ
class JSONDataProcessor extends DataProcessor {
@Override
protected void loadData(String data) {
System.out.println("Loading data from JSON file: " + data);
}
@Override
protected boolean isValidData(String data) {
return data != null;
}
@Override
protected void processData(String data) {
System.out.println("Processing JSON data");
}
@Override
protected void saveData(String data) {
System.out.println("Saving JSON data to database");
}
}