2006-04-28
Refactoring 笔记 - 对第一个案例的再重构
案例中 Movie 的 setPriceCode 方法还是存在着 case 语句,站在代码美学的角度上来讲这显然是不可容忍的,而且对以后的扩展也不是很方便。比如现在要加一种 Price 策略需要修改哪些地方?首先加入一个 Price subclass,那个 case 是肯定要修改的,还要加一个 priceCode 常量,好麻烦,即然都 Strategy 了,那就 Stragegy 到底。
把所有的 Price subclass 的 getProceCode 方法里面返回自已所代表的ProceCode
public class ChildrensPrice extends Price {
public int getPriceCode() {
return 2;
}
}
public class ChildrensPrice extends Price {
public int getPriceCode() {
return 2;
}
}
public class NewReleasePrice extends Price {
public int getPriceCode() {
return 1;
}
}
public int getPriceCode() {
return 1;
}
}
public class RegularPrice extends Price {
public int getPriceCode() {
return 0;
}
}
public int getPriceCode() {
return 0;
}
}
修改 Movie 中常量定义为
public final static Price REGULAR = new RegularPrice();
public final static Price CHILDRENS = new ChildrensPrice();
public final static Price NEW_RELEASE = new NewReleasePrice();
public final static Price REGULAR = new RegularPrice();
public final static Price CHILDRENS = new ChildrensPrice();
public final static Price NEW_RELEASE = new NewReleasePrice();
修改 Movie 的构造方法为,注意:这里修改了对外的接口,除非能做到不用修改客户端程序,否则在实际项目中要酌情处理
public Movie(String name, Price price) {
_title = name;
_price = price;
}
public Movie(String name, Price price) {
_title = name;
_price = price;
}
这样 setPriceCode 就没用了,干掉,现在程序看起来爽多了
run 你的测式
done......
发表评论
- 浏览: 13848 次
- 性别:

- 来自: wuhan

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
Eclipse 找不到插件的问题
在configuration/config.ini里加上一个参数:osgi.ch ...
-- by iceworld4143 -
关于IE(frameset)导致cook ...
楼主,太感谢您了!我被这个问题折磨了一天一夜,看了您的这篇文章,问题迎刃而解!如 ...
-- by lumi -
关于IE(frameset)导致cook ...
太感谢了!我被这个问题都折磨疯了,几天都找不出问题,特别是在客户那边部署时候出这 ...
-- by zwchen -
[转]在中国搞技术只能混 ...
留倒青山在,慢慢敖咧...
-- by dgates -
简化struts配置
变得更复杂
-- by boogie






评论排行榜