案例中 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......