Intention
Defines the skeleton of an algorithm in an operation, and delays some steps into subclasses. The Template method allows subclasses to redefine some specific steps of the algorithm without altering the structure of an algorithm.
Refers to: An abstract class, there is a main method, and then define 1...N methods, can be abstract, can also be the actual method, define a class, inherit the abstract class, override the abstract method, by invoking the abstract class, implement the Call of the child class
Public abstract class Abstractcalculator { /* Main method, which implements calls to other methods of this class * /public final int calculate (String exp,string opt) { int array[] = split (exp,opt); Return calculate (array[0],array[1]); } /* Method overridden by the quilt class * /abstract public int calculate (int num1,int num2); Public 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; } }
public class Plus extends Abstractcalculator { @Override public int calculate (int num1,int num2) { return num 1 + num2; } }
Test
public class Strategytest {public static void Main (string[] args) { String exp = "8+8"; Abstractcalculator cal = new Plus (); int result = Cal.calculate (exp, "\\+"); SYSTEM.OUT.PRINTLN (result); } }
Transferred from: http://blog.csdn.net/zhangerqing/article/details/8243942
Java Learning notes-design pattern 15 (Template method mode)