A Template method pattern provides a skeleton for performing any sort of algorithm or an operation, and it allows the sub-classes to re-define part of the logic.
Good Hypothetical E.g.: https://www.journaldev.com/1763/template-method-design-pattern-in-java
- HTTPServlet is an example of template method pattern.The doXXX methods in HttpServlet are called from the service method.
In other words, we have a template method (
service) deferring some of its processing to individual methods defined in sub-classes. These methods are selected at compile time, so this is an example of the template method pattern.
DVD Player Example:
DVD Player can read CD’s, DVD’s & Blue-Ray's. Apparently, the play() logic for every media source is same: read → modulate → output.
But the read part may vary for different media source. This variance could be defined within the sub-class specific to the media source.
Implementation in Java
- Create abstract generalization class which includes skeleton logic.
2. Create Specialization which defines variable part of skeleton logic.
3. Driver to test this out.
Found it Interesting?
Please show your support by 👏. To read the complete series, click below.
I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄