Junior — Middle
How is the 'Template Method' pattern implemented in the Spring framework?
sobes.tech AI
Answer from AI
In Spring, the "Template Method" pattern is implemented through abstract classes and hooks, where the base class defines a common algorithm, and subclasses override specific steps. For example, in the Spring Framework, there is a class JdbcTemplate that sets the template for working with JDBC: opening a connection, executing a query, processing the result, and closing resources. The user only overrides the part related to result processing (for example, via RowMapper).
An example of a simplified template method:
public abstract class AbstractProcessor {
public void process() {
stepOne();
stepTwo();
stepThree();
}
protected abstract void stepOne();
protected void stepTwo() {
// common step, can be overridden
System.out.println("Default step two");
}
protected abstract void stepThree();
}
public class ConcreteProcessor extends AbstractProcessor {
@Override
protected void stepOne() {
System.out.println("Custom step one");
}
@Override
protected void stepThree() {
System.out.println("Custom step three");
}
}
Thus, Spring uses this pattern to encapsulate repetitive operations and provide extension points.