测试一种便捷开发的模型,常用于数据库的D、层次。其中用到反射来获取泛型参数。
首先定义一个Generictor接口,定义接口方法。
/**
*
*/
package com.zjq.container;
/**
* @author zhangjiaqi
* 写一个生成器接口
*
*/
public interface Generator<T> {
/**
* @return
* 返回一个T所对应的实例
*/
public T next();
}
然后实现类,
然后实现类:
package com.zjq.container;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GeneratorImpl<T> implements Generator<T>{
@SuppressWarnings("unchecked")
@Override
public T next() {
Type t=this.getClass().getGenericSuperclass();
Type actualTypeArguments=((ParameterizedType)t).getActualTypeArguments()[0];
try {
Class<?> c3= (Class<?>) actualTypeArguments;
return (T) c3.newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
}
CatDao类:
package com.zjq.container;
public interface CatDao extends Generator<Cat>{
}
CatDao的实现类:
package com.zjq.container;
public class CatDaoImpl extends GeneratorImpl<Cat> implements CatDao{
}
测试类:
package com.zjq.container;
public class Test {
public static void main(String[] args) {
CatDaoImpl catDaoImpl=new CatDaoImpl();
System.out.println(catDaoImpl.next().getName());
}
}
输出:
猫
假如Cat这个类是数据库的对应的类,使用这种模式可以增加Dog类,Fox类等,
而只需要定义相应的接口即可,实现类都集成在GeneratorImpl中,扩展方便,集成度也很高。