`

模版方法模式

 
阅读更多

一、核心思想

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

关系图:

 

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

测试类:

 

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

 

二、何时使用

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

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

 

三、Java的应用

HTTP请求处理类HttpServlet

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics