I've been reading Design Patterns, by Gamma et al. I have a question concerning the Template Method as compared to Dependency Injection.
With Template Method, you "template" classes with policies that provide alternatives for needed actions or calculations. So rather than choosing one policy from several alternatives and coding that policy into the class, you allow the user of the class to specify the alternative they want to use.
It all sounds very reasonable to me. But I hit a bit of a conceptual brick wall.
If you instantiate a class with a policy object, the policy object needs to implement an abstract interface. The programmer can then write different policies that all compile into the class without error because the policies implement the interface. The class using the policies is coded to the policy interface and not the implementation.
If you're going to define an abstract IPolicy
for these policy objects, why not just use Dependency Injection and pass in the IPolicy
on construction?
Can anyone shed any light on why you would prefer the Template Method to Dependency Injection?