Reputation: 1056
Recently in a interview I was explaining about a framework that i have worked on. I said that we created a inversion of control by providing extensiblity using template method design pattern. I said this was an example of Inversion of Control where our framework was calling the methods implemented by the user of framework, to which interviewer said that a template method design pattern is not an example of IOC. I wonder if my understanding of IOC is incorrect ?
Upvotes: 10
Views: 2190
Reputation: 997
Yes, template pattern is an example of IOC and IOC can be achieved using Template pattern as well along with few other techniques(DI etc.). In inheritance child classes call the methods from parent classes but using template pattern we define an algorithm (sequence of steps which cannot be changed by child classes) using a final method implementation in base class as per shown in example mentioned below, Base/Parent class is calling methods which will be defined in child classes so control is inverted and base class has the control over the core algorithm, so this is why and where IOC is achieved in this case.
Example - Lets say we need to process a file.
public abstract class FileProcessor {
public final void processFile() {
preProcess();
process();
postProcess();
}
public abstract void preProcess();
public abstract void process();
public abstract void postProcess();
}
Upvotes: 3
Reputation: 93444
Your interviewer was wrong. The template method pattern does use inversion of control. In fact, the Wikipedia entry specifically mentions it.
http://en.wikipedia.org/wiki/Template_method_pattern
The template method is used in frameworks, where each implements the invariant parts of a domain's architecture, leaving "placeholders" for customisation options. This is an example for inversion of control, also called the Hollywood principle.
Unfortunately, you either didn't understand IoC or the Template method pattern well enough to explain to them why it was an example of IoC. Unfortunately, many people seem to think IoC means Dependency Injection, and that's it.
Upvotes: 9