http://blog.csdn.net/shihengli2010/article/details/51784993
参考下列代码:
- <prices>
- <price code="1" classname="com.test.RegularPrice" />
- <price code="2" classname="com.test.ChildrensPrice" />
- <price code="3" classname="com.test.NewReleasePrice" />
- </prices>
上面的为if...else... 改写版本,可放入配置文件中,然后通过解析xml文件来获取对应的price
下面代码即为通过反射来获取对应的price,代码写的很漂亮,值得学习.
- import java.util.HashMap;
- import java.util.Map;
-
- public class PriceConfig {
-
- private int code;
- private Class<Price> clazz;
- private static Map<Integer, PriceConfig> map = new HashMap<Integer, PriceConfig>();
-
- PriceConfig(int code, String classname) {
- this.code = code;
- this.clazz = initClass(classname);
- register(this);
- }
-
- @SuppressWarnings("unchecked")
- private Class<Price> initClass(String classname) {
- Class<Price> clazz = null;
- try {
- clazz = (Class<Price>)Class.forName(classname);
- } catch (ClassNotFoundException e) {
- throw new IllegalArgumentException(classname + " isnot exist");
- }
- if(!clazz.isAssignableFrom(Price.class)) {
- throw new IllegalArgumentException(classname + " isnot Price implementation");
- }
- return clazz;
- }
-
- private static void register(PriceConfig priceConfig) {
- map.put(priceConfig.getCode(), priceConfig);
- }
-
- public static Price getPrice(int code) {
- PriceConfig price = map.get(code);
- if(price == null) {
- new IllegalArgumentException("Incorrect Price Code");
- }
- return price.getPrice();
- }
-
- public int getCode() {
- return code;
- }
-
- public Class<Price> getClassname() {
- return clazz;
- }
-
- public Price getPrice() {
- try {
- return (Price)clazz.newInstance();
- } catch (InstantiationException e) {
- throw new Xxxxxxxxx();
- } catch (IllegalAccessException e) {
- throw new Xxxxxxxxx();
- }
- }
- }
3:以后代码直接这样就可以用了:
Price price = PriceConfig.getPrice(CHILDRENS);
经过这样的改造之后就是一个符合“开-闭原则”的易扩展、低耦合的功能了,呵呵。