示例:
Customer类:
int num;
public int getPrice(){
int result;
switch(getFruit.getPriceCode){
case:Fruit.APPLE:
result = num * 4;
break;
case:Fruit.BANANA:
result = num*7;
break;
}
return result;
}
重构:
1.将 weight*num*4,抽取成一个方法 getCharge();消除result局部变量。
public int getCharge(int price){
return num * price;
}
2.如果Customer类判断switch语句的条件,都来自Fruit类的常量。
则switch语句应该移动到Fruit类中
Fruit.getCharge(int num);
3.Fruit类的常量应该用继承,用多态处理
产生继承于Fruit的Apple,Banana子类。Fruit中抽象方法为getCharge();
Fruit.getCharge(int num); Apple.getCharge(int num); Banan.getCharge(int num);
4.如果在另一种情况下Fruit可以变为Apple和Banana(当然这个例子是不可能了) (这种做法叫Replace Type Code with State/Strategy)
则应该用state或strategy模式:
抽取出类Type,有抽象方法getCharge().它的子类AppleType,BananaType来实现这个方法。
(而用State、Strategy,取决于Type代表的是水果的种类,还是水果计费方式~~~~这个我也不太明白)
总结:
State模式用法
1.抽取出状态建立结构 (Replace Type Code with State/Strategy)
如给Fruit设置FruitType字段,有getType()方法。FruitType有个工厂方法根据不同的int值,返回不同的子类。但FruitType还没有getCharge()方法(即只有状态,而无状态导致的行为)
1.移动状态产生的行为(switch语句)到FruitType中(实际行为)
FruitType添加getCharge()
2.消除Fruit中的switch语句用多态 (Replace Conditional with Polymorphism)
getPrice(){
mFruitType.getCharge()
}
本文探讨了如何通过重构代码结构和应用设计模式来优化软件开发过程。具体包括将重量级计算抽取到独立方法、将状态逻辑移至具体类中以减少switch语句的使用,并介绍了状态模式(State)和策略模式(Strategy)的应用场景。此外,文章还讨论了如何通过继承和多态来简化复杂的业务逻辑,从而提高代码的可读性和维护性。
4467

被折叠的 条评论
为什么被折叠?



