1、类图
2、实现
抽象工厂模式,通过反射实例化,可将具体的实现方式放入配置文件中。
public abstract class AbstractExport {
protected String exportType;
public abstract void export();
}
public class SyncExport extends AbstractExport {
public SyncExport() {
super.exportType = "SYNC";
}
@Override
public void export() {
System.out.println("export type:" + super.exportType);
}
}
public class AsyncExport extends AbstractExport {
public AsyncExport() {
super.exportType = "ASYNC";
}
@Override
public void export() {
System.out.println("export type:" + super.exportType);
}
}
public interface IExportFactory {
AbstractExport createExport(String exportType);
AbstractExport createExportFormClass(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException;
}
public class CentosExportFactory implements IExportFactory{
public CentosExportFactory() {
System.out.println("CentosExportFactory");
}
public AbstractExport createExport(String exportType) {
AbstractExport export = null;
switch (exportType) {
case "SYNC":
export = new SyncExport();
break;
case "ASYNC":
export = new AsyncExport();
break;
}
return export;
}
public AbstractExport createExportFormClass(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
AbstractExport export = (AbstractExport) Class.forName(className).newInstance();
return export;
}
}
public class WindowsExportFactory implements IExportFactory{
public WindowsExportFactory() {
System.out.println("WindowsExportFactory");
}
public AbstractExport createExport(String exportType) {
AbstractExport export = null;
switch (exportType) {
case "SYNC":
export = new SyncExport();
break;
case "ASYNC":
export = new AsyncExport();
break;
}
return export;
}
public AbstractExport createExportFormClass(String className) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
AbstractExport export = (AbstractExport) Class.forName(className).newInstance();
return export;
}
}
public class ExportTest {
public static void main(String[] args) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
// IExportFactory iExportFactory = new WindowsExportFactory();
IExportFactory iExportFactory = (IExportFactory) Class.forName(WindowsExportFactory.class.getName()).newInstance();
AbstractExport export = iExportFactory.createExport("SYNC");
export.export();
AbstractExport exportClass = iExportFactory.createExportFormClass(SyncExport.class.getName());
exportClass.export();
}
}