Junior — Middle
What task does the Design Pattern Methodical Structure perform?
sobes.tech AI
Answer from AI
The "Template Method" design pattern is used to define the skeleton of an algorithm in a base class, allowing subclasses to override certain steps of the algorithm without changing its overall structure. This helps to avoid code duplication and promotes reuse of common logic.
Example in Java:
abstract class DataProcessor {
// Template method
public final void process() {
readData();
processData();
saveData();
}
abstract void readData();
abstract void processData();
void saveData() {
System.out.println("Saving data to database");
}
}
class CSVDataProcessor extends DataProcessor {
void readData() {
System.out.println("Reading data from CSV file");
}
void processData() {
System.out.println("Processing CSV data");
}
}
Here, the process() method defines the overall algorithm, while the specific steps are implemented in subclasses.