结合反射应用,使用class.forName反射创建对象,通过泛型约束参数类型
新产品只需实现CommonAPI即可,无需修改工厂
public abstract class CommonGenerator{
public abstract <T extends CommonAPI>T genCommon(Class<T> tClass) throws Exception;
/**
* 只需实现此接口
*/
public interface CommonAPI{
String getSomething();
}
}
public class CommonFactory extends CommonGenerator {
@Override
public <T extends CommonAPI> T genCommon(Class<T> tClass) throws Exception {
CommonAPI commonInfo = (CommonAPI) Class.forName(tClass.getName()).newInstance();
return (T)commonInfo;
}
}
测试
public class IPhone implements CommonGenerator.CommonAPI{
@Override
public String getSomething() {
return "this is Iphone";
}
}
public class Test {
public static void main(String []s) throws Exception {
String r =new CommonFactory().genCommon(IPhone.class).getSomething();
System.out.print(r);
}
}