2

Please consider a StringBank class. This class holds a list of Strings and can return them to the client.

It's code (irrelevant stuff omitted):

abstract class StringBank{

    List<String> strings;

    public List<String> getStrings(){

        for(String string : strings){
            if(!stringValid(string)){
                strings.remove(string);
            }
        }

        return strings;

    }

    public abstract boolean stringValid(String s);

}

As you can see, stringValid is an abstract method, meant to be implemented by the subclasses. This way subclasses serve as 'filters' of the string bank, filtering out invalid strings (e.g. a particular subclass may return false for strings that end with an 'a').

My question is: is this considered an implementation of the Template Method design pattern?

The purpose of Template Method is to define steps of an algorithm in an abstract superclass, and have the subclasses define the implementation of some of these steps.

Usually, the 'template method' - where the algorithm is defined, would look something like this:

void algorithm(){
    step1(); // implemented in this class
    step2(); // implemented in this class
    step3(); // abstract method, implemented in subclasses.
    step4(); // implemented in this class
}

However in StringBank, the algorithm is very simple, so it only involves one method call: stringValid(). The rest of the steps of the algorithm are defined in the method itself (looping through the strings, removing strings and returning them).

getStrings() doesn't really 'look like' a 'template method', so I'm not sure if this is considered a Template Method pattern implementation.

The algorithm could be described as:

  1. For each string:

    1.1. Check if valid. (implemented by the subclasses).

    1.2. If invalid, remove from list.

  2. Return list of strings.

Would you define the implementation I described as an implementation of the Template Method design pattern, even though getStrings() doesn't 'feel' like a classic template method?

Aviv Cohn
  • 21,190
  • 31
  • 118
  • 178

1 Answers1

0

This is the template method pattern. In this example though, composition should be preferred over inheritence; use the strategy pattern.

Do not make your StringBank abstract, but give it a string validator filter function as parameter.

phil
  • 29
  • 3