抽象工厂
抽象工厂是对简单工厂的进一步的抽象结果。
使用抽象工厂模式的系统会涉及到下面角色:
1.抽象工厂
这个角色是抽象工厂模式的核心,任何模式中创建对象的工厂类必须实现这个接口。
2.具体工厂
实现了抽象工厂的具体java类,具体工厂角色和业务密切相关,随着使用者调用创建。
3.抽象产品
抽象工厂创建的对象的父类
4.具体产品
实现了抽象产品,是工厂创建的实例。
抽象工厂的实例
抽象工厂
public interface ExportFactory {
public ExportFile factory(String type);
}
html工厂
public class ExportHtmlFactory implements ExportFactory {
public ExportFile factory(String type) {
if ("standard".equals(type)) {
return new ExportStandardHtmlFile();
} else if ("financial".equals(type)) {
return new ExportFinancialHtmlFile();
}
return null;
}
}
pdf工厂
public class ExportPdfFactory implements ExportFactory {
public ExportFile factory(String type) {
if ("standard".equals(type)) {
return new ExportStandardPdfFile();
} else if ("financial".equals(type)) {
return new ExportFinancialPdfFile();
}
return null;
}
}
抽象导出文件
public interface ExportFile {
public boolean export(String data);
}
具体导出文件
public class ExportFinancialHtmlFile implements ExportFile {
public boolean export(String data) {
System.out.println("导出财务版HTML文件");
return false;
}
}
public class ExportFinancialPdfFile implements ExportFile{
public boolean export(String data) {
System.out.println("导出财务版PDF文件");
return false;
}
}
public class ExportStandardHtmlFile implements ExportFile{
public boolean export(String data) {
System.out.println("导出标准HTML文件");
return false;
}
}
public class ExportStandardPdfFile implements ExportFile{
public boolean export(String data) {
System.out.println("导出标准PDF文件");
return false;
}
}
main
public class Main {
public static void main(String[] args) {
String data = "";
ExportFactory factory = new ExportHtmlFactory();
ExportFile file = factory.factory("standard");
file.export(data);
}
}
结果
导出标准HTML文件