博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java实现23种设计模式之模版方法模式
阅读量:4323 次
发布时间:2019-06-06

本文共 1103 字,大约阅读时间需要 3 分钟。

先看代码:

package com.ceshi13;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 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;    }}
package com.ceshi13;public class Plus extends AbstractCalculator {    @Override    public int calculate(int num1, int num2) {        return num1 + num2;    }}
package com.ceshi13;public class StrategyTest {    public static void main(String[] args) {        String exp = "8+8";        AbstractCalculator cal = new Plus();        int result = cal.calculate(exp, "\\+");        System.out.println(result);    }}

运算结果:

上面抽象类的代码中有calculate方法,是可以通过不同的子类继承并且重写的,这就相当于模版

定义了模版,至于具体是怎么子的通过子类实现

转载于:https://www.cnblogs.com/zhengyuanyuan/p/10755990.html

你可能感兴趣的文章
初识ionic
查看>>
java 中打印调用栈
查看>>
开发 笔记
查看>>
数据挖掘算法比赛 - 简单经验总结
查看>>
win7(64位)php5.5-Apache2.4-mysql5.6环境安装
查看>>
生成商户订单号/退款单号
查看>>
使用Android OpenGL ES 2.0绘图之六:响应触摸事件
查看>>
我们过去几年做对了哪些事
查看>>
ubuntu 16.04LTS
查看>>
javascript深入理解js闭包
查看>>
Oracle的安装
查看>>
Android Socket连接PC出错问题及解决
查看>>
Android Studio-—使用OpenCV的配置方法和demo以及开发过程中遇到的问题解决
查看>>
第2天线性表链式存储
查看>>
python自动化测试-D11-学习笔记之一(yaml文件,ddt)
查看>>
mysql存储过程使用游标循环插入数据
查看>>
Ubuntu 12.04 添加新用户并启用root登录
查看>>
shell中$0,$?,$!等的特殊用法
查看>>
20145309信息安全系统设计基础第9周学习总结上
查看>>
c# 字段、属性get set
查看>>