ITeye博客

模版方法模式

ldaolong · 2014-10-08 08:19 · Design Patterns · 非技术 · Markdown

一、核心思想

让抽象类给出程序的骨架和轮廓,在抽象类中编写主方法,并申明一些抽象方法,迫使子类实现剩余逻辑。

关系图:

 

  1. public abstract class AbstractCalculator {
  2. /*主方法,实现对本类其它方法的调用*/
  3. public final int calculate(String exp,String opt){
  4. int array[] = split(exp,opt);
  5. return calculate(array[0],array[1]);
  6. }
  7. /*被子类重写的方法*/
  8. abstract public int calculate(int num1,int num2);
  9. public int[] split(String exp,String opt){
  10. String array[] = exp.split(opt);
  11. int arrayInt[] = new int[2];
  12. arrayInt[0] = Integer.parseInt(array[0]);
  13. arrayInt[1] = Integer.parseInt(array[1]);
  14. return arrayInt;
  15. }
  16. }

[java] view plaincopy

  1. public class Plus extends AbstractCalculator {
  2. @Override
  3. public int calculate(int num1,int num2) {
  4. return num1 + num2;
  5. }
  6. }

测试类:

 

 

  1. public class StrategyTest {
  2. public static void main(String[] args) {
  3. String exp = "8+8";
  4. AbstractCalculator cal = new Plus();
  5. int result = cal.calculate(exp, "\\+");
  6. System.out.println(result);
  7. }
  8. }

 

二、何时使用

所谓模版方法模式,就是父类完全控制着子类的业务逻辑,而子类根据不同的业务对父类的所有抽象方法进行实现。

适合场景:知道一个算法所有关键步骤,并确定了这些步骤的执行顺序,但某些步骤的具体实现时未知的。

 

三、Java的应用

HTTP请求处理类HttpServlet

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。