前两篇文章介绍了结合静态代理和简单工厂对策略进行应用,这里介绍使用反射方式应用策略模式。
定义反射策略类:
/**
* @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。