重构之对象替代函数

今天看到replace method with method object时,觉得有点问题,如果只是单纯提炼一个新class的话,过于简洁,应该对这个新类的作用域做个限制:

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();
}


-----
代码只是为了表达思路,所以粗糙了些。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值