“Replace Method with Method Object”(以函数对象取代函数)。其做法是将函数放进一个单独的对象当中,使用这个单独对象的值域(filed)来替代原函数中的局部变量。这样做的好处是对于一个拥有较多较复杂的局部变量的函数来说的。
- package neusoft;
- /**
- * <p>Date : 2012-03-15</p>
- * <p>Description: 以函数对象取代函数,解决局部变量过多问题</p>
- * @author 小俊垃圾回收站
- *
- */
- public class ReplaceMethodWithMethodObject {
- /*原来未重构代码
- 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 - 2 * importantValue1;
- }*/
- /**
- * 重构后
- */
- int gamma(int inputVal, int quantity, int yearToDate) {
- // 将工作委托给函数对象
- return new Gamma(inputVal, quantity, yearToDate).gamma();
- }
- private int delta() {
- return 5;
- }
- /*
- * replace method with inner class method object(could be better than outer
- * class!)
- */
- class Gamma {
- private int inputVal;
- private int quantity;
- private int yearToDate;
- private int importantValue1;
- private int importantValue2;
- private int importantValue3;
- public Gamma(int inputVal, int quantity, int yearToDate) {
- this.inputVal = inputVal;
- this.quantity = quantity;
- this.yearToDate = yearToDate;
- }
- int gamma() {
- importantValue1 = (inputVal * quantity) + delta();
- importantValue2 = (inputVal * yearToDate) + 100;
- importantValue2 = importantThing();
- importantValue3 = importantValue2 * 7;
- return importantValue3 - 2 * importantValue1;
- }
- private int importantThing() {
- if ((yearToDate - importantValue1) > 100) {
- importantValue2 -= 20;
- }
- return importantValue2;
- }
- }
- /**
- * test
- *
- * @param args
- */
- public static void main(String[] args) {
- System.out.print(new ReplaceMethodWithMethodObject().gamma(1, 1, 1));
- }
- }
本文参照《重构改善代码的设计》
——————————————————————————————————————————小俊垃圾回收站
转载于:https://blog.51cto.com/12772226/806873