今天看到replace method with method object时,觉得有点问题,如果只是单纯提炼一个新class的话,过于简洁,应该对这个新类的作用域做个限制:
--
这里面有个问题,如果getA()是private的话,那么这样写,重构就失败了,因为要改getA()的private才行。
这个时候,内部类的作用就出现了,下面是内部类的写法
这里是调用
--------------------
-----
代码只是为了表达思路,所以粗糙了些。
public class A {
/*
* 待重构函数
*/
public int b(int c, int d, int e) {
int f = c * d + this.getA();
return f - e;
// return new B(c,d,e).doB();
}
public int getA() {
return 100;
}
// private int getA(){
// return 100;
// }
}
/*
* 重构的新类
*/
public class B {
private A a;
private int c;
private int d;
private int e;
private int f;
/**
* 构造函数
*
* @param c
* @param d
* @param e
*/
public B(int c, int d, int e) {
this.c = c;
this.d = d;
this.e = e;
}
/*
* 迁移的方法
*/
public int doB() {
f = c * d + a.getA();
return f - e;
}
}
--
这里面有个问题,如果getA()是private的话,那么这样写,重构就失败了,因为要改getA()的private才行。
这个时候,内部类的作用就出现了,下面是内部类的写法
public class A {
/*
* 待重构函数
*/
public int b(int c, int d, int e) {
// int f = c * d + this.getA();
// return f - e;
return new C(c, d, e).doC();
}
private int getA() {
return 100;
}
/*
* 一个内部类
*/
public class C {
private A a;
private int c;
private int d;
private int e;
private int f;
/**
* 构造函数
*
* @param c
* @param d
* @param e
*/
public C(int c, int d, int e) {
this.c = c;
this.d = d;
this.e = e;
}
/*
* 迁移的方法
*/
public int doC() {
f = c * d + a.getA();
return f - e;
}
}
}
这里是调用
--------------------
public static void main(String[] a) {
C c = new A().new C(1, 2, 3);
c.doC();
}
-----
代码只是为了表达思路,所以粗糙了些。