使用场景
模板方法模式是类的行为模式。准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。这就是模板方法模式的用意。
代码例子
模板类
public abstract class Template {
/* 主方法,实现对本类其它方法的调用 */
public final int calculate(String exp, String opt) {
int array[] = split(exp, opt);
return calculate(array[0], array[1]);
}
/* 被子类重写的方法 */
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 Template {
@Override
public int calculate(int num1, int num2) {
return num1 + num2;
}
}
main函数
public class Test {
public static void main(String[] args) {
String exp = "8+8";
Template cal = new Plus();
int result = cal.calculate(exp, "\\+");
System.out.println(result);
}
}