Java设计模式(七)策略模式 模板模式

(十三)策略模式

策略模式定义了多个封装起来的算法,封装的算法可以相互替换,并且算法的变化不会影响到使用算法的客户。借用另一位大神的例子。

interface ICalculator{
	public int calculate(String exp);
}
abstract class AbstractCalculator{
	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 implements ICalculator{
	public int calculate(String exp){
		int arrayInt[] = split(exp, "\\+");
		return arrayInt[0]+arrayInt[1];
	}
}
class Minus extends AbstractCalculator implements ICalculator{
	public int calculate(String exp){
		int arrayInt[] = split(exp,"-");
		return arrayInt[0] = arrayInt[1];
	}
}
class Multiply extends AbstractCalculator implements ICalculator{
	public int calculate(String exp){
		int arrayInt[] = split(exp,"\\*");
		return arrayInt[0] * arrayInt[1];
	}
}
public class Strategy {
	public static void main(String[] args){
		String exp = "2*8";
		ICalculator cal = new Multiply();
		System.out.println(cal.calculate(exp));
	}
}
系统提供不同算法的实现,对于各种算法封装好,用户决定使用哪个算法。策略模式多使用在算法决策系统中,例如电子商务价格算法。跟抽象类很相似,我感觉。

(十四)模板方法模式

模板方法的意义是一个父类方法提供大部分的算法,子类完成剩余的算法。父类调用子类的实现。

abstract class TemplateCalc{
	//主方法
	public final int calculate(String exp,String opt){
		int array[] = split(exp,opt);
		return calculate(array[0],array[1]);
	}
	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;
	}
	abstract public int calculate(int num1,int num2);
}
class PlusTemp extends TemplateCalc{
	public int calculate(int num1,int num2){
		return num1 + num2;
	}
}
public class Template{
	public static void main(String[] args){
		TemplateCalc tem = new PlusTemp();
		System.out.println(tem.calculate("12*23", "\\*"));
	}
}
将一个子类初始化,调用父类的 calculate 方法,父类执行完分解,调用子类的相加,其实 * 并不代表乘,只是个切分符号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值