模板方法模式-Template Method

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

  • 定义一个抽象的计算器类
public abstract class AbstractCalculator {  
      
    public final int calculate(String exp,String opt){  
        int array[] = split(exp,opt);  
        return calculate(array[0],array[1]);  
    }  
      
    abstract public int calculate(int a,int b);  

    public int[] split(String exp,String splitor){  
        String array[] = exp.split(splitor);  
        if(array.length != 2)
            throw new RuntimeException("error");

        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 a,int b) {  
        return a + b;  
    }  
}
  • 定义减法类
public class Minus extends AbstractCalculator {  
  
    @Override  
    public int calculate(int a, int b) {  
        return a - b;  
    }  
}
  • 测试
public class Main {  
  
    public static void main(String[] args) {  
        String exp = "8+8";  
        AbstractCalculator cal = new Plus();  
        int result = cal.calculate(exp, "\\+");  
        System.out.println(result);

        exp = "8-8";
        cal = new Minus();  
        result = cal.calculate(exp, "-");  
        System.out.println(result);  
    }  
}

程序执行结果:

16
0

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

详细代码戳这里

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容