---
title: "Pluggable Adapters"
author: "SunMicro"
date: "2007-04-09T21:34:00Z"
tags: []
slug: "pluggable-adapters"
draft: false
lastmod: "2007-04-09T21:34:00Z"
id: 69351
url: "https://gossip.iteye.com/blog/69351"
---

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 代码

01. /*
02. \*Adaptee
03. \*/
04. class Pathfinder
05. {
06. public void explore()
07. {
08. System.out.println("explore");
09. }
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 代码

01. public class PluggableAdapterDemo
02. {
03. public PluggableAdapterDemo()
04. {
05. }
06. public static void main(String\[] args)
07. {
08. Pathfinder pathfinder=new Pathfinder();
09. PluggablePathfinderAdapter adapter=new PluggablePathfinderAdapter(pathfinder);
10. adapter.adapt("Digger","dig");
11. adapter.adapt("Collector","collect");
12. adapter.explore("Digger");
13. }
14. }