Search code examples
javagenericstemplate-method-pattern

How can I loop through a List<T> using the template-method pattern?


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.


Solution

  • 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:

    public abstract class TemplateMethodLoop<T> {
        public abstract void execute(T t);
    
        public void loop(List<T> array) {
            for (T t : array) {
                this.execute(t);
            }
        }
    }
    
    public class TemplateMethodPatternClient {
        public void stringListPrinter(List<String> stringList) {
            new TemplateMethodLoop<String>() {
                public void execute(String string) {
                    System.out.println(string);
                }
            }.loop(stringList);
        }
    }
    

    Note that in this case the concrete implementation of the required behavior lies in the anonymous inner class within the stringListPrinter() method which extends the TemplateMethodLoop superclass.