前两篇文章介绍了结合静态代理和简单工厂对策略进行应用,这里介绍使用反射方式应用策略模式。
定义反射策略类:
/**
* @author alex
*
*/
public class StratagemReflection {
private AbstractDao dao;
public StratagemReflection(String className) throws Exception{
try {
this.dao = (AbstractDao)Class.forName(className).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public Object getObject(){
return dao.getById();
}
}
Client应用策略:
public static void testStratagemRef(){
try {
// StratagemReflection stratagem = new StratagemReflection("dp.HibernateDao");
// StratagemReflection stratagem = new StratagemReflection("dp.IbatitsDao");
StratagemReflection stratagem = new StratagemReflection("dp.stratagem.JdbcDao");
System.out.println(stratagem.getObject());
} catch (Exception e) {
e.printStackTrace();
}
}
一般情况下会使用properties文件或xml文件,配置具体的策略实现类,通过对配置文件的修改实现策略之间的切换,而不需要对具体的代码进行修改,如
spring中PropertyPlaceholderConfigurer。
分享到:
相关推荐
供初学反射的开发者提供一个小例子,希望各位多多指点
由于最近在做C#方面的开发,自己也开始看一些C#方面的书籍。看到不解处也时常google一下,此文确实是我无意间看到的一篇好文章,希望对大家有所帮助
设计模式之 Strategy(策略) 不同算法各自封装,用户端可随意挑选需要的算法. 设计模式之 Chain of Responsibility(责任链) 各司其职的类串成一串,好象击鼓传花,当然如果自己能完成,就不要推委给下一个. 设计模式...
Reflection 是 Java 程序开发语言的特征之一,它允许运行中的 Java...JavaBean 是 reflection 的实际应用之一,它能让一些工具可视化的操作软件组件。这些工具通过 reflection 动态的载入并取得 Java 组件(类) 的属性。
Exploiting Reflection Change for Automatic Reflection Removal.去除像反光
反射(Reflection)是C#里很重要的一个特性,源码是我写的一篇关于反射的文章的示例,有详细的解释,是学习反射的好实例。
让你轻松搞定Reflection(反射)
Java Reflection in Action is unique in presenting a clear account of all the cool things you can do with reflection, and at the same time pro- viding the sound conceptual basis that developers need to...
JAVA REFLECTION IN ACTION
java reflection 内容学习
Unity Planar Reflection平面反射
java reflection in action 2005 英文版
详细解说reflection 和annotation
C#反射(Reflection)详解 什么是反射 命名空间和装配体的关系
reflection的ppt介绍,当中包括大学课程reflection的详细讲解
Laravel开发-reflection 模块说明