Template Method Pattern in Java

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

GenericServlet vs HTTPServlet

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 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.

  1. Create abstract generalization class which includes skeleton logic.

MediaDisk.com

2. Create Specialization which defines variable part of skeleton logic.

DVDMediaDisk.java

CDMediaDisk.java

3. Driver to test this out.

Found it Interesting?
Please show your support by 👏. To read the complete series, click below.

Disclaimer:
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 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store