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");
    }
}