- 抽象工厂类或接口
public abstract class AbstractFactory {
public abstract <T extends IProduct> T createProduct(Class<T> c);
}
- 抽象工厂类或接口实现类
public class ConcreteFactory extends AbstractFactory {
@Override
public <T extends IProduct> T createProduct(Class<T> c) {
T product = null;
try {
product = (T) Class.forName(c.getName()).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
return product;
}
}
- 抽象产品类或接口
public interface IProduct {
public void doSomething();
}
- 抽象产品类或接口实现类
public class ConcreteProduct1 implements IProduct {
@Override
public void doSomething() {
//具体操作
}
}
- 使用
IProduct product = new ConcreteFactory().createProduct(ConcreteProduct1.class);
product.doSomething();