如何通过反射来代替N多的if...else

http://blog.csdn.net/shihengli2010/article/details/51784993

参考下列代码:


[java]  view plain  copy
  1. <prices>  
  2.   <price code="1" classname="com.test.RegularPrice" />  
  3.   <price code="2" classname="com.test.ChildrensPrice" />  
  4.   <price code="3" classname="com.test.NewReleasePrice" />  
  5. </prices>  

上面的为if...else... 改写版本,可放入配置文件中,然后通过解析xml文件来获取对应的price





下面代码即为通过反射来获取对应的price,代码写的很漂亮,值得学习.

[java]  view plain  copy
  1. import java.util.HashMap;  
  2. import java.util.Map;  
  3.   
  4. public class PriceConfig {  
  5.   
  6.     private int code;  
  7.     private Class<Price> clazz;  
  8.     private static Map<Integer, PriceConfig> map = new HashMap<Integer, PriceConfig>();  
  9.   
  10.     PriceConfig(int code, String classname) {  
  11.         this.code = code;  
  12.         this.clazz = initClass(classname);  
  13.         register(this);  
  14.     }  
  15.   
  16.     @SuppressWarnings("unchecked")  
  17.     private Class<Price> initClass(String classname) {  
  18.         Class<Price> clazz = null;  
  19.         try {  
  20.             clazz = (Class<Price>)Class.forName(classname);  
  21.         } catch (ClassNotFoundException e) {  
  22.             throw new IllegalArgumentException(classname + " isnot exist");  
  23.         }  
  24.         if(!clazz.isAssignableFrom(Price.class)) {  
  25.             throw new IllegalArgumentException(classname + " isnot Price implementation");  
  26.         }  
  27.         return clazz;  
  28.     }  
  29.   
  30.     private static void register(PriceConfig priceConfig) {  
  31.         map.put(priceConfig.getCode(), priceConfig);  
  32.     }  
  33.   
  34.     public static Price getPrice(int code) {  
  35.         PriceConfig price = map.get(code);  
  36.         if(price == null) {  
  37.             new IllegalArgumentException("Incorrect Price Code");  
  38.         }  
  39.         return price.getPrice();  
  40.     }  
  41.   
  42.     public int getCode() {  
  43.         return code;  
  44.     }  
  45.   
  46.     public Class<Price> getClassname() {  
  47.         return clazz;  
  48.     }  
  49.   
  50.     public Price getPrice() {  
  51.         try {  
  52.             return (Price)clazz.newInstance();  
  53.         } catch (InstantiationException e) {  
  54.             throw new Xxxxxxxxx();  
  55.         } catch (IllegalAccessException e) {  
  56.             throw new Xxxxxxxxx();  
  57.         }  
  58.     }  
  59. }  


3:以后代码直接这样就可以用了:

Price price = PriceConfig.getPrice(CHILDRENS);

经过这样的改造之后就是一个符合“开-闭原则”的易扩展、低耦合的功能了,呵呵。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值