2007-04-09
Pluggable Adapters
关键字: design pattern 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 代码
- /*
- *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();
- }
- }
- }
java 代码
- 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");
- }
- }
- 21:34
- 浏览 (477)
- 评论 (0)
- 分类: Impure Gossip
- 相关推荐
发表评论
- 浏览: 5707 次

- 详细资料
搜索本博客
最近加入圈子
最新评论
-
圣诞,也来凑个热闹!
米国同样有很强的商业味比如圣旦....老头的红袄是由可口可乐公司赞助的.还有可恶 ...
-- by 抛出异常的爱 -
圣诞,也来凑个热闹!
pluto_t 写道没记错的话应该是二氧化硫?臭鸡蛋味 二氧化氮也还是有刺激味道 ...
-- by SunMicro -
圣诞,也来凑个热闹!
恩,恩,中国城市里的圣诞节气氛很浓,都是瞎热闹,问10个人有8个人不知道圣诞节的 ...
-- by ouspec -
圣诞,也来凑个热闹!
没记错的话应该是二氧化硫?臭鸡蛋味
-- by pluto_t -
圣诞,也来凑个热闹!
seen 写道>>聞起来才知道夹了点一氧化碳 在通常状况下,一氧化碳是无色、无 ...
-- by SunMicro






评论排行榜