I’m looking for an example implementation of the template-method pattern in Java. Suppose, for example, I’d like to create a generic class that can loop through a List<T> and execute a template method with signature void execute(T t) on each item of type T in the list.
I’m looking for an example implementation of the template-method pattern in Java. Suppose, for
Share
There is a quite clear Java example in the Wikipedia article for the Template method pattern.
The basic concept of the pattern is that the variable parts of the code are broken out in separate methods. That allows the shared parts to remain in a superclass, while the descendant classes implement the methods that correspond to the variable parts, providing different behavior as required.
If you wanted to stay close to the commonly accepted implementation of the pattern, your code should be along these lines:
Note that in this case the concrete implementation of the required behavior lies in the anonymous inner class within the
stringListPrinter()method which extends theTemplateMethodLoopsuperclass.