31天重构指南之三: 提升方法(pull up )
2009-09-16 09:30
661 查看
提升方法的重构是指将方法提升到继承链的较高层次,该重构一般发生了当一个方法需要被更多的继承链中的多个实现使用时。
1:publicabstractclassVehicle
2:{
3://othermethods
4:}
5:
6:publicclassCar:Vehicle
7:{
8:publicvoidTurn(Directiondirection)
9:{
10://codehere
11:}
12:}
13:
14:publicclassMotorcycle:Vehicle
15:{
16:}
17:
18:publicenumDirection
19:{
20:Left,
21:Right
22:}
在上面的代码中,Turn方法只存在于Car类中,所以我们在Motorcycle类中无法使用Turn方法,如果我们想在Motorcycle类中使用Turn方法,则需要将Turn方法提升到Vehicle类中,
这样Vehicle所有的子类都可以使用Turn方法,这样做的一个缺点是我们增加了Vehicle类的复杂性。因些只有当一个方法需要被类的多个子类使用时,才考虑将方法提升到基类中。
另外面向对象的设计也不提倡过多的使用继承,而是提倡优先使用组织(composition)。下面是重构后的代码:
1:publicabstractclassVehicle
2:{
3:publicvoidTurn(Directiondirection)
4:{
5://codehere
6:}
7:}
8:
9:publicclassCar:Vehicle
10:{
11:}
12:
13:publicclassMotorcycle:Vehicle
14:{
15:}
16:
17:publicenumDirection
18:{
19:Left,
20:Right
21:}
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/03/refactoring-day-3-pull-up-method.aspx
相关文章推荐
- 31天重构学习笔记3. 提升方法
- 31天重构指南之二十二:分解方法
- 31天重构指南之十:提取方法
- 31天重构学习笔记3. 提升方法
- 31天重构学习笔记3. 提升方法
- 31天重构指南之二十八:为布尔方法命名
- 重构手法58:Pull Up Method (方法上移)
- 31天重构指南之五:提升字段
- 31天重构学习笔记3. 提升方法
- 31天重构指南之四:降低方法(pull down)
- 31天重构指南之二:移动方法
- 31天重构指南之十三:提取方法对象
- 重构第5天:提升字段(Pull Up Field)
- 重构3-Pull Up Method(方法上移)
- 重构第3天:方法提公(Pull Up Method)
- 6 个重构方法可帮你提升 80% 的代码质量
- 31天重构学习笔记7. 重命名(方法,类,参数)
- 31天重构学习笔记22. 分解方法
- 6 个重构方法可帮你提升 80% 的代码质量
- 六个重构方法可帮你提升80%的代码质量