Template Method Design Pattern
Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure (DoFactory).
- When behavior of an algorithm can vary, you let sub-classes implement the behavior through overriding
- You want to control the point that sub-classing is allowed
- You want to avoid code duplication, implementing variations of the algorithm in sub-classes
I think you need to be cautious about item 3, because template method reduce code duplication using shared methods in base class and it could lead to deep inheritance coupling; If your code duplication could be put in a separate class, then you can can use shared component as a delegation. In Another word, do not clutter up your base classes by putting seemingly unrelated codes!
- Well applicable in frameworks: They invoke so called hook methods, which provide default behavior which sub-classes can extend if necessary. It’s important for template methods to specify which methods are hooks (may be overridden) and which are abstract operations (must be overridden).
- A fundamental technique for code reuse, for example, in class libraries.
- Leads to an inverted control structure that’s sometimes referred to as the “Hollywood principle,” that is, “Don’t call us, we call you”.
- Difficult to compose functionality: When inheritance is used as the way to add new functionality, it becomes impossible to add functionality in more than one axis at the same time without defining more and more classes.
- Difficult to maintain: Having maintained a couple chunks of code that made extensive use of the template method, it can be challenging. Changes at any one level can disturb operation above or below that level in the template methods.
- Alternative: define an interface for each kind of functionality and inject an instance for each. Typically these interfaces are factories and strategies. You can then mix and match each piece separately and also insert interceptors to handle functionality like logging, pooling, caching, etc.
- Factory Method is a specialization of Template Method.
- Factory Methods are often called by template methods.
- Strategy: Template methods use inheritance to vary part of an algorithm. Strategies use delegation to vary the entire algorithm.
- Strategy modifies the logic of individual objects. Template Method modifies the logic of an entire class.