Sobes.tech
Junior — Middle

Could you explain the concept of the template method and its application in development?

sobes.tech AI

Answer from AI

The Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class method, leaving some steps of the algorithm to be implemented in subclasses.

This allows subclasses to override certain parts of the algorithm without changing its overall structure.

Example of application: the base class describes a general process, such as data processing, while specific steps (e.g., reading data, processing it, and saving) are implemented in subclasses.

Example in Java:

abstract class DataProcessor {
    // template method
    public final void process() {
        readData();
        processData();
        saveData();
    }

    abstract void readData();
    abstract void processData();
    abstract void saveData();
}

class CSVProcessor extends DataProcessor {
    void readData() { System.out.println("Reading CSV"); }
    void processData() { System.out.println("Processing CSV"); }
    void saveData() { System.out.println("Saving CSV"); }
}

This approach ensures code reuse and flexibility when expanding functionality.