Replace Method with Method Object 以函数对象取代函数

以函数对象取代函数
使用场景: 你有一个大型函数,其中对局部变量的使用使你无法采用Extract Method.
解决方法:将这个函数放进一个单独的对象中,如此一来局部变量就变成了对象内字段,然后可以在同一个对象将这个大型函数分解为多个小型函数。
代码解释:

package 第六章;

public class Account {
	//重构前:较为大型的函数体
	int gamma(int inputVal, int quantity, int yearToDate) {
		int importantValue1 = (inputVal * quantity) + delta();
		int importantValue2 = (inputVal * yearToDate) + 100;
		if ((yearToDate - importantValue1) > 100)
			importantValue2 -= 20;
		int importantValue3 = importantValue2 * 7;
		return importantValue3 - importantValue1 * 2;

	} 
	int delta() {
		return 1;
	}
	
	//重构后:提取Gamma对象,并将计算需要的变量仍以参数的方式传递过去,将计算的过程提取函数进行计算
	int gamma(int inputVal,int quantity,int yearToDate){
	return new Gamma(this,inputVal,quantity,yearToDate).compute();
}

	class Gamma {
		private final Account account;
		private int inputVal;
		private int quantity;
		private int yearToDate;
		private int importantValue1;
		private int importantValue2;
		private int importantValue3;

		public Gamma(Account source, int inputVal, int quantity, int yearToDate) {
			super();
			this.account = source;
			this.inputVal = inputVal;
			this.quantity = quantity;
			this.yearToDate = yearToDate;
			this.importantValue1 = importantValue1;
			this.importantValue2 = importantValue2;
			this.importantValue3 = importantValue3;
		}

		int compute() {
			importantValue1 = (inputVal * quantity) + account.delta();
			importantValue2 = (inputVal * yearToDate) + 100;
			importantValue3 = importantValue2 * 7;
			return importantValue3 - importantValue1 * 2;
		}
		//可以轻松使用Extract Method()的方式提取函数,不必担心传递参数的问题
		void importantThing(){
			if ((yearToDate - importantValue1) > 100)
				importantValue2 -= 20;
		}
	}
	
	public static void main(String[] args) {
		Account a = new Account();
		int result = a.gamma(100, 100, 100);
		System.out.println("result: "+result);
		
	}
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值