模板方法模式

  一个抽象类中,有一个主方法,再定义1...n个方法,可以是抽象的,也可以是实际的方法,定义一个类,继承该抽象类,重写抽象方法,通过调用抽象类,实现对子类的调用。

/**
 * 
 * @author: muyichun
 * @date  : 2016年3月23日15:07:32
 * @function: 模板方法模式
 */
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);
	}
}

abstract class AbstractCalculator{
	//主方法,实现对本类其它方法的调用
	public final int calculate(String exp, String opt){
		int array[] = split(exp, opt);
		return calculate(array[0], array[1]);
	}
	
	//被子类重写的方法
	public abstract 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;
	}
}

class Plus extends AbstractCalculator{

	@Override
	public int calculate(int num1, int num2) {
		
		return num1 + num2;
	}
}
——贴上自己喜欢的代码!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值