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.
- /*
- *Adaptee
- */
- class Pathfinder
- {
- public void explore()
- {
- System.out.println("explore");
- }
- }
- /*
- *Target
- */
- class Digger
- {
- public void dig()
- {
- System.out.println("Dig");
- }
- }
- /*
- *Target
- */
- class Collector
- {
- public void collect()
- {
- System.out.println("collect");
- }
- }
- /*
- *Adapter
- */
- class PluggablePathfinderAdapter
- {
- private Pathfinder pathfinder;
- private HashMap map=new HashMap();
- PluggablePathfinderAdapter(Pathfinder pathfinder)
- {
- this.pathfinder=pathfinder;
- }
- public void adapt(String classname,String methodname)
- {
- try
- {
- Class _class=Class.forName(classname);
- Method method=_class.getMethod(methodname,null);
- map.put(classname,method);
- }catch(ClassNotFoundException cnfe)
- {
- cnfe.printStackTrace();
- }catch(NoSuchMethodException nsme)
- {
- nsme.printStackTrace();
- }
- }
- public void explore(String classname)
- {
- try
- {
- pathfinder.explore();
- map.get(classname).invoke(Class.forName(classname).newInstance(),null);
- }catch(Exception e)
- {
- e.printStackTrace();
- }
- }
- }
- public class PluggableAdapterDemo
- {
- public PluggableAdapterDemo()
- {
- }
- public static void main(String[] args)
- {
- Pathfinder pathfinder=new Pathfinder();
- PluggablePathfinderAdapter adapter=new PluggablePathfinderAdapter(pathfinder);
- adapter.adapt("Digger","dig");
- adapter.adapt("Collector","collect");
- adapter.explore("Digger");
- }
- }
插拔式适配器
本文介绍了一种名为插拔式适配器的设计模式,该模式允许适配器动态地适应多个不同的类。通过使用Java反射机制,适配器能够识别目标类的方法并调用它们。文中提供了一个具体的实现示例,展示了如何为不同类的目标方法创建适配器。
30

被折叠的 条评论
为什么被折叠?



