Pluggable Adapters

A pluggable adapter is an adapter that adapts dynamically to one of several classes. Of course, the adapter can adapt only to classes that it can recognize, and usually the adapter decides which class it is adapting to based on differing constructors or setParameter methods.

Java has yet another way for adapters to recognize which of several classes it must adapt to: reflection. You can use reflection to discover the names of public methods and their parameters for any class. For example, for any arbitrary object you can use the getClass method to obtain its class and the getMethods method to obtain an array of the method names.

java 代码
  1. /*
  2. *Adaptee
  3. */
  4. class Pathfinder
  5. {
  6. public void explore()
  7. {
  8. System.out.println("explore");
  9. }
  10. }
  11. /*
  12. *Target
  13. */
  14. class Digger
  15. {
  16. public void dig()
  17. {
  18. System.out.println("Dig");
  19. }
  20. }
  21. /*
  22. *Target
  23. */
  24. class Collector
  25. {
  26. public void collect()
  27. {
  28. System.out.println("collect");
  29. }
  30. }
  31. /*
  32. *Adapter
  33. */
  34. class PluggablePathfinderAdapter
  35. {
  36. private Pathfinder pathfinder;
  37. private HashMap map=new HashMap();
  38. PluggablePathfinderAdapter(Pathfinder pathfinder)
  39. {
  40. this.pathfinder=pathfinder;
  41. }
  42. public void adapt(String classname,String methodname)
  43. {
  44. try
  45. {
  46. Class _class=Class.forName(classname);
  47. Method method=_class.getMethod(methodname,null);
  48. map.put(classname,method);
  49. }catch(ClassNotFoundException cnfe)
  50. {
  51. cnfe.printStackTrace();
  52. }catch(NoSuchMethodException nsme)
  53. {
  54. nsme.printStackTrace();
  55. }
  56. }
  57. public void explore(String classname)
  58. {
  59. try
  60. {
  61. pathfinder.explore();
  62. map.get(classname).invoke(Class.forName(classname).newInstance(),null);
  63. }catch(Exception e)
  64. {
  65. e.printStackTrace();
  66. }
  67. }
  68. }

java 代码
  1. public class PluggableAdapterDemo
  2. {
  3. public PluggableAdapterDemo()
  4. {
  5. }
  6. public static void main(String[] args)
  7. {
  8. Pathfinder pathfinder=new Pathfinder();
  9. PluggablePathfinderAdapter adapter=new PluggablePathfinderAdapter(pathfinder);
  10. adapter.adapt("Digger","dig");
  11. adapter.adapt("Collector","collect");
  12. adapter.explore("Digger");
  13. }
  14. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值