Introduction to the Template pattern of Java design patterns

  • 2020-04-01 03:42:07
  • OfStack

Template pattern definition: defines the skeleton of an algorithm in an operation, deferring the execution of some steps to its subclasses.

In fact, Java's abstract class is the Template pattern, so use is common. And it's easy to understand and use, so let's start with an example:


public abstract class Benchmark
{
  /**
  * Here's what we want to do in a subclass
  */
  public abstract void benchmark();   /**
  * repeat benchmark The number of
  */
  public final long repeat (int count) {
    if (count <= 0)
      return 0;
    else {
      long startTime = System.currentTimeMillis();
            for (int i = 0; i < count; i++)
          benchmark();
                long stopTime = System.currentTimeMillis();
                return stopTime - startTime;
          }
        }
}

In the example above, we wanted to repeat the benchmark() operation, but instead of specifying what benchmark() was, we deferred the description to its subclass:

public class MethodBenchmark extends Benchmark
{
  /**
  * Really define benchmark content
  */
  public void benchmark() {
    for (int i = 0; i < Integer.MAX_VALUE; i++){
      System.out.printtln("i="+i);    
       }
  }
}


At this point, the Template pattern is complete, isn't it simple? See how to use:


   Benchmark operation = new MethodBenchmark();
    long duration = operation.repeat(Integer.parseInt(args[0].trim()));
    System.out.println("The operation took " + duration + " milliseconds");

Maybe you used to wonder what abstract classes are good for, but now you've figured it all out? As for the benefits of doing this, it's obvious that it's extensible, and since I can change the content of Benchmark later, I just need to make one more subclass without having to change any other application code.


Related articles: