设计模式-模版模式

使用场景

模板方法模式是类的行为模式。准备一个抽象类,将部分逻辑以具体方法以及具体构造函数的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现。这就是模板方法模式的用意。
在这里插入图片描述

代码例子

模板类

public abstract class Template {
/* 主方法,实现对本类其它方法的调用 */
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;
}
}

加法

public class Plus extends Template {
@Override
public int calculate(int num1, int num2) {
return num1 + num2;
}
}

main函数

public class Test {
public static void main(String[] args) {
String exp = "8+8";
Template cal = new Plus();
int result = cal.calculate(exp, "\\+");
System.out.println(result);
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值