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. }

你可能感兴趣的:(design pattern)