抽象工厂模式创建对象

结合反射应用,使用class.forName反射创建对象,通过泛型约束参数类型
新产品只需实现CommonAPI即可,无需修改工厂

public abstract class CommonGenerator{

    public abstract T genCommon(Class tClass) throws Exception;

    /**
     * 只需实现此接口
     */
    public interface CommonAPI{
        String getSomething();
    }
}
public class CommonFactory extends CommonGenerator {

    @Override
    public  T genCommon(Class 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);
    }

}

你可能感兴趣的:(抽象工厂模式创建对象)