标准代码
1.先建立一个抽象工厂类
public abstract class AbstarctFactory {
public abstract <T extends AbstractProduct> T createProduct(Class<T> c);
}
2.建立一个抽象产品类
public abstract class AbstractProduct {
//产品类的公共方法
public void method1(){
//业务逻辑处理
}
public abstract void method2();
}
3.建立一个具体工厂类
public class FactoryRealize extends AbstarctFactory{
@Override
public <T extends AbstractProduct> T createProduct(Class<T> c) {
AbstractProduct product = null;
try {
product = (AbstractProduct) Class.forName(c.getName()).newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return (T) product;
}
}
4.建立具体产品类
public class Product extends AbstractProduct {
@Override
public void method2() {
}
}
5.模拟场景测试
public class Client {
public static void main(String[] args){
AbstarctFactory factoryRealize = new FactoryRealize();
AbstractProduct products = factoryRealize.createProduct(Product.class);
products.method2();
}
}
注意:具体实际抽象模式的创建要具体实际需求去扩展