Sometimes in software development, this is the case, the implementation of a function requires multiple steps, these steps are very clear (what is the first step, what is the second step ...) For example, make a dish: the first step is to wash the vegetables, the second is to cut the vegetables, the third step is to set the plate); Some of these steps are fixed (for example, washing dishes – washing them with blisters, placing plates – putting them on a plate), and some of the steps are uncertain (for example, cutting-cut, diced, sliced ...). )。 So there is the template method pattern, there is an abstract class in the template method pattern, there is a final method in the abstract class, used to complete a function (such as making a dish), but also have to complete the various steps of this function (such as washing vegetables, cutting dishes, plate), and in these methods to represent the various steps, Those that can be determined are specific, and those that are not deterministic are defined as abstract methods that are implemented in subclasses.
Package mode.template_method;/** * * This defines an abstract computer class with a final method to complete the calculation, which first calls the split operation, separates the numbers, and then calls the calculation method to calculate, * Specifically to do what kind of calculation, in the subclass to implement * * */public abstract class Abstractcalculator {/* Main method, the implementation of other methods of this class */public final int calculate (string exp, string opt) {int array[] = split (exp, opt); return calculate (Array[0], array[1]);} /* Methods overridden by quilt class */abstract public int calculate (int num1, int num2);p ublic int[] Split (string exp, string opt) {string array[] = Exp.split (opt); int arrayint[] = new Int[2];arrayint[0] = Integer.parseint (array[0]); arrayint[1] = Integer.parseint ( ARRAY[1]); return arrayint;}}
Package mode.template_method;/** * * This implements a subclass of compute addition * * */public class Plus extends Abstractcalculator {@ overridepublic int calculate (int num1, int num2) {//TODO auto-generated method Stubreturn num1 + num2;}}
Test
Package Mode.template_method;public class Test {public static void main (string[] args) {String exp = "8+8"; Abstractcalculator plus = new Plus (); SYSTEM.OUT.PRINTLN (Plus.calculate (exp, "\\+"));}}
Template method Mode