zoukankan      html  css  js  c++  java
  • 模板方法模式-Template Method

    模板方法模式是指:一个抽象类中,有一个主方法(一般为final),再定义其他抽象的或是具体的方法,由主方法来调用这些方法,然后定义其子类,重写其抽象方法,通过调用抽象类,实现对子类的调用

    先定义一个抽象的计算器类:

     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 a,int b);  
     9 
    10     public int[] split(String exp,String splitor){  
    11         String array[] = exp.split(splitor);  
    12         if(array.length != 2)
    13             throw new RuntimeException("error");
    14 
    15         int arrayInt[] = new int[2];  
    16         arrayInt[0] = Integer.parseInt(array[0]);  
    17         arrayInt[1] = Integer.parseInt(array[1]);  
    18         return arrayInt;  
    19     }  
    20 } 

    加法类:

    1 public class Plus extends AbstractCalculator {  
    2   
    3     @Override  
    4     public int calculate(int a,int b) {  
    5         return a + b;  
    6     }  
    7 }

    减法类:

    1 public class Minus extends AbstractCalculator {  
    2   
    3     @Override  
    4     public int calculate(int a, int b) {  
    5         return a - b;  
    6     }  
    7 }

    测试类:

     1 public class Main {  
     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         exp = "8-8";
    10         cal = new Minus();  
    11         result = cal.calculate(exp, "-");  
    12         System.out.println(result);  
    13     }  
    14 } 

    程序执行结果:

    16
    0

    模板方法即是:在类本身无法实现或者各子类有不同的实现方式时,将方法抽象化暴露给子类去实现。

  • 相关阅读:
    测试杂谈
    使用jQuery完成表单验证
    session&&cookie
    jQuery中关于toggle的使用
    Regist&Login
    关于线程的面试题
    成语验证码所需素材
    验证码测试-demo
    java动态生成验证码图片
    servlet-向页面输出中文出现乱码处理方式
  • 原文地址:https://www.cnblogs.com/joshua-aw/p/6048873.html
Copyright © 2011-2022 走看看